USB连接时停用服务

时间:2011-12-10 11:39:20

标签: android android-service

我怀疑当USB连接到PC时是否可以停止服务?

if(intent.getAction().equals(Intent.ACTION_UMS_DISCONNECTED)) {
     Intent intent2=new Intent(context,MyService.class);
     context.startActivity(intent2);
}
else if (intent.getAction().equals( Intent.ACTION_UMS_CONNECTED)) {
     stopService(new Intent(this, MyService.class));
}

我已经这样做了,但它没有用。

1 个答案:

答案 0 :(得分:2)

尝试另一个广播接收器;

public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    // UsbManager.ACTION_USB_STATE -> "android.hardware.usb.action.USB_STATE" actually
    if (action.equals(UsbManager.ACTION_USB_STATE)) {
        Bundle extras = intent.getExtras();
        // UsbManager.USB_CONNECTED -> "connected" actually
        usbConnected = extras.getBoolean(UsbManager.USB_CONNECTED);
        ...

希望这有帮助。