Skip to content

Most visited

Recently visited

navigation

确定和监控插接状态和基座类型

Android 设备可插接到几个不同种类的基座,其中包括汽车或家用基座以及数字和模拟基座。 插接状态通常与充电状态联系密切,因为许多基座都为插接的设备供电。

手机插接状态对更新频率的影响取决于您的应用。您可以选择在手机插入桌面基座时提高体育中心应用的更新频率,或者在设备插入车载手机座时完全停用更新。 相反,如果您的后台服务正在更新交通状况,则您可以选择在已插接车载基座的情况下最大限度提高更新频率。

插接状态也以粘性 Intent 形式广播,以便您查询设备是否已插接以及已插接情况下的插接类型。

确定当前插接状态

插接状态详情以 extra 形式包含在 ACTION_DOCK_EVENT 操作的粘性广播中。由于它是粘性广播,因此您无需注册 BroadcastReceiver。如下一段代码中所示,您只需调用 registerReceiver(),将 null 作为广播接收器传入。

IntentFilter ifilter = new IntentFilter(Intent.ACTION_DOCK_EVENT);
Intent dockStatus = context.registerReceiver(null, ifilter);

您可以从 EXTRA_DOCK_STATE extra 中提取当前插接状态:

int dockState = battery.getIntExtra(EXTRA_DOCK_STATE, -1);
boolean isDocked = dockState != Intent.EXTRA_DOCK_STATE_UNDOCKED;

确定当前基座类型

如果设备已插接,其插接的基座可能为以下四种不同类型之一:

请注意,后两种类型从 Android 的 API 级别 11 才开始引入,因此如果您只关注基座类型而不关心其具体为数字还是模拟形式,则最好检查所有三种类型:

boolean isCar = dockState == EXTRA_DOCK_STATE_CAR;
boolean isDesk = dockState == EXTRA_DOCK_STATE_DESK ||
                 dockState == EXTRA_DOCK_STATE_LE_DESK ||
                 dockState == EXTRA_DOCK_STATE_HE_DESK;

监控插接状态或基座类型变化

每当设备插入或拔出基座时,都会广播 ACTION_DOCK_EVENT 操作。如需监控设备的插接状态变化,只需如下面的代码段所示,在您的应用清单文件中注册一个广播接收器:

<action android:name="android.intent.action.ACTION_DOCK_EVENT"/>

您可以使用上一步中介绍的相同技巧提取接收器实现内的基座类型和插接状态。

This site uses cookies to store your preferences for site-specific language and display options.

Get the latest Android developer news and tips that will help you find success on Google Play.

* Required Fields

Hooray!

Browse this site in ?

You requested a page in , but your language preference for this site is .

Would you like to change your language preference and browse this site in ? If you want to change your language preference later, use the language menu at the bottom of each page.

This class requires API level or higher

This doc is hidden because your selected API level for the documentation is . You can change the documentation API level with the selector above the left navigation.

For more information about specifying the API level your app requires, read Supporting Different Platform Versions.

Take a short survey?
Help us improve the Android developer experience.
(Sep 2017 survey)