Detect USB in Broadcastreceiver - what am I missin

2019-07-04 16:12发布

问题:

My code misses something, need your eyes to locate.

I created a USBOnReciever broadcastreceiver.

public class USBOnReceiver extends BroadcastReceiver
{ 
@Override
public void onReceive(Context context, Intent intent) 
{
    Toast.makeText(context,  "Phone was connected to power" ,Toast.LENGTH_LONG).show();
    Log.d("tag", "Phone was connected to power");
} 
} 

My manifest is:

<application>
    <receiver android:name=".USBOnReceiver" android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.UMS_CONNECTED" />
        </intent-filter>
    </receiver>

</application>

and here is when I stuck. nothing appears to happen when connecting the USB ( I also tried with power_connected).

I understand I can register the BR either through the manifest or programmaticaly. But not sure how to implement.

In my activity I added

        USBOnReceiver myReceiver = new USBOnReceiver();

But it looks so unconnected and useless :-/

Will appreciate your eyes here.

回答1:

Your code is seems complete. If im not mistaken, the only issue you have is: You wrote reciever inside your manifest instead of receiver. So the BroadcastReceiver never got registered correctly.

To the topic of registering in code:

Yeah thats possible. Just create an instance of your receiver and use Context.registerReceiver(mReceiver, new IntentFilter(...)).

If you have registered in your manifest, there is no need to do that. BroadcastReceivers only live for the execution of onReceive(). Therefore the system creates the instances and kills them afterwards.