拔下USB设备时停止服务

时间:2013-06-03 13:46:28

标签: android

我想在拔掉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也被称为。{/ p>

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

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

但是没有调用分离。

2 个答案:

答案 0 :(得分:5)

当手机/平板电脑上的USB设备(不是电缆)脱落时,会发出嗯.. ACTION_USB_DEVICE_DETACHED。这不是你想要的。

我不知道是否有用于检测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
        }
    }
}

答案 1 :(得分: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);
相关问题