Detect USB in Broadcastreceiver - what am I missing?

亡梦爱人 提交于 2019-12-10 18:46:40

问题


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.



来源:https://stackoverflow.com/questions/6486339/detect-usb-in-broadcastreceiver-what-am-i-missing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!