[英]How to detect my android device is connected with usb or car dock through Broadcast Receiver?
我正在尝试使用Broadcast Receiver使我的设备连接到USB或汽车坞,但未得到正确的结果。 请帮忙? 提前致谢。 接收方代码为:
public class CarDockReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Car Dock Receiver registerd", Toast.LENGTH_SHORT).show();
switch (intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)) {
case BatteryManager.BATTERY_PLUGGED_AC:
Toast.makeText(context, "Battery plugged AC", Toast.LENGTH_SHORT).show();
break;
case BatteryManager.BATTERY_PLUGGED_USB:
Toast.makeText(context, "Battery plugged USB", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
}
清单文件中的接收者为:
<receiver
android:name=".CarDockReceiver"
android:enabled="true" >
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
</intent-filter>
</receiver>
刚刚解决了检测USB设备插入的类似问题。 事实证明-因为您在清单中指定了一个意图过滤器-插入某些东西后Android会调用onResume。您可以尝试添加以下内容:
@Override
protected void onResume() {
super.onResume();
Intent intent = getIntent();
if (intent != null) {
Log.d("onResume", "intent: " + intent.toString());
if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
// Do your thing ...
}
运行它以查看确切记录的内容,并使用该信息来检查要检查的正确操作(在上面的示例中,在此处替换ACTION_USB_DEVICE_ATTACHED)。
要检查您的设备是否已连接到USB附件,可以使用此意图。
<activity ...>
...
<intent-filter>
<action android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" />
</intent-filter>
<meta-data android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED"
android:resource="@xml/accessory_filter" />
</activity>
参考: http : //developer.android.com/guide/topics/connectivity/usb/accessory.html
如果您仅检测到USB连接,则将这些意图用于意图过滤器:UsbManager.ACTION_USB_DEVICE_ATTACHED和UsbManager.ACTION_USB_DEVICE_DETACHED
希望这可以帮助。
更新:
如果要处理的是带有电源的附件,则还可以使用以下意图检测连接:ACTION_POWER_CONNECTED。 当外部电源已连接到设备时,将广播此意图。 这是示例代码。
在您的AndroidManifest.xml中
<receiver android:name=".YourReceiver" >
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.BATTERY_CHANGED" />
</intent-filter>
</receiver>
和您的receive.java源:
public class YourReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("connection", "power connected");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.