Android USB Host mode service - Start based on USB_DEVICE_ATTACHED

后端 未结 3 731
一个人的身影
一个人的身影 2021-02-10 03:20

I want to write a service in Android which starts based on USB_DEVICE_ATTACHED intent. So, basically my service should start when a specific USB Device(FT232C - VID:PID 0403:601

相关标签:
3条回答
  • 2021-02-10 03:52

    From my experience a <service> cannot receive the USB intents. I overcame this by creating a hidden activity to receive the intent and re-broadcast it. Of course this activity could also handle starting/stopping your service.

    I have already put up some working code here:
    https://stackoverflow.com/a/15151075/588476
    You will just have to change it so it starts and stops your service automatically.

    0 讨论(0)
  • 2021-02-10 03:55

    Yes, it is very well possible, sorry to say that you are using wrong intent-filter in your reveiver tag in AndroidManifest.xml. Let me guide you

    AndroidManifest.xml

    .
    .
    .
    <receiver android:name=".DetactUSB">
       <intent-filter>
            <action android:name="android.intent.action.UMS_CONNECTED" />
            <action android:name="android.intent.action.UMS_DISCONNECTED" />
       </intent-filter>
    </receiver>
    

    BroadcastReceiver file

    public class DetactUSB extends BroadcastReceiver
    { 
        private static final String TAG = "DetactUSB";
        @Override
        public void onReceive(Context context, Intent intent) 
        {
            // TODO Auto-generated method stub
            if (intent.getAction().equalsIgnoreCase( "android.intent.action.UMS_CONNECTED"))
            {
                    // Fire your Intent to start Activity
                    Log.i(TAG,"USB connected..");
            }
            if (intent.getAction().equalsIgnoreCase( "android.intent.action.UMS_DISCONNECTED"))
            {
            }
        } 
    }
    
    0 讨论(0)
  • 2021-02-10 03:59

    I believe the main problem is the number base for the vendor and product id's. The format in the device filter xml should be decimal, so vendor-id="1025" and product-id="24592".

    Aside from that, it absolutely should be USB_DEVICE_ATTACHED, rather than UMS_CONNECTED (the latter is not USB host mode at all).

    I don't have the authoritative answer as to whether a service could receive a broadcast intent, or whether you have to use an activity for that, but it seems like Wayne Uroda has good experience with this question.

    0 讨论(0)
提交回复
热议问题