我想检测手机是否插入电脑或将被拔出......所以在我的清单中我有:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="de.name.usbtest.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
</activity>
<service
android:name=".MyService"
>
</service>
</application>
我的服务等级:
@Override
public void onCreate() {
USBBroadcast usbTrigger = null;
// create new USBTrigger()() and register for ACTION_USB_DEVICE_ATTACHED broadcasts
usbTrigger = new USBBroadcast();
registerReceiver(usbTrigger, new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED));
}
我的广播接收器:
@Override
public void onReceive(Context ctx, Intent intent) {
String action = intent.getAction();
Toast.makeText(ctx, "Received", Toast.LENGTH_SHORT).show();
}
和我的主要活动:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent serviceIntent = new Intent(this, MyService.class);
startService(serviceIntent);
setContentView(R.layout.activity_main);
}
但是当我插入手机时,我从来没有看到过吐司……有人知道为什么吗?!