2013-06-03 132 views
1

我想在拔掉USB插頭時停止正在運行的服務。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> 

但是detach沒有被調用。

回答

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); 
+0

OK,但是當活動是發生了什麼在後臺,還是被摧毀? – user1940676

+1

註冊接收器則用於服務;) – Dediqated

+0

如果你不想從活動開始廣播接收器 - 在AndroidManifest.xml – msh

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 
     } 
    } 
} 
+0

如何從一個BroadcastReceiver類停止正在運行的服務?? 而我正在運行一個USB設備作爲主機。 – user1940676

+0

使用stopService() – ozbek

+0

謝謝,我錯過了作爲參數傳遞的上下文,但設備是否會被分離也會被調用? – user1940676