1

我想在拔下 USB 时停止正在运行的服务。

在我的活动onCreate中,我检查其意图action

    if (getIntent().getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
        Log.d(TAG, "************** USB unplugged stopping  service **********");
        Toast.makeText(getBaseContext(), "usb was disconneced", Toast.LENGTH_LONG).show();
        stopService(new Intent(this, myService.class));
    } else {
        init();
    }

在我的里面我manifest有另一个intent filter

        <intent-filter>
            <action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" />
        </intent-filter>

intent filter也是被调用的。

        <intent-filter>
            <category android:name="android.intent.category.DEFAULT" />

            <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
        </intent-filter>

但是没有调用分离。

4

2 回答 2

5

嗯..ACTION_USB_DEVICE_DETACHED当 USB 设备(不是电缆)从手机/平板电脑上断开时触发。这不是你想要的。

我不知道是否有用于检测 USB 电缆连接的直接 API,但您可以使用ACTION_POWER_CONNECTEDACTION_POWER_DISCONNECTED实现您的目标。

为您的接收器使用以下过滤器:

<intent-filter>
    <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
    <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
</intent-filter>

在你的接收器中,你可以检查状态并实现你想要的逻辑:

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        switch(intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)) {
            case 0: 
                // The device is running on battery
                break;
            case BatteryManager.BATTERY_PLUGGED_AC:
                // Implement your logic
                break;
            case BatteryManager.BATTERY_PLUGGED_USB:
                // Implement your logic
                break;
            case BATTERY_PLUGGED_WIRELESS:
                // Implement your logic
                break;
            default:
                // Unknown state
        }
    }
}
于 2013-06-03T14:17:08.973 回答
4

您需要注册一个 BroadcastReceiver

    BroadcastReceiver receiver = new BroadcastReceiver() {
       public void onReceive(Context context, Intent intent) {
          if(intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
              Log.d(TAG, "************** USB unplugged stopping  service **********");
              Toast.makeText(getBaseContext(), "usb was disconneced", 
                  Toast.LENGTH_LONG).show();
                  stopService(new Intent(this, myService.class));
           }
        };

    IntentFilter filter = new IntentFilter();
    filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
    registerReceiver(receiver, filter);
于 2013-06-03T14:11:24.713 回答