检测USB在广播接收器 - 我缺少什么? [英] Detect USB in Broadcastreceiver - what am I missing?

查看:147
本文介绍了检测USB在广播接收器 - 我缺少什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的code惦记的东西,需要你的眼睛找到。

My code misses something, need your eyes to locate.

我创建了一个USBOnReciever广播接收器。

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");
} 
} 

我的清单是:

<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>

和这里是我卡住了。
没有出现在连接USB时,发生(我也试图与power_connected)。

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

我明白我可以通过清单或programmaticaly的BR注册。但不知道如何实现。

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

在我的活动我添加

        USBOnReceiver myReceiver = new USBOnReceiver();

但它看起来如此悬空无用: - /

But it looks so unconnected and useless :-/

威尔AP preciate在这里你的眼睛。

Will appreciate your eyes here.

推荐答案

您code是完全看来。如果我没错的话,
你唯一的问题是:你写你的清单,而不是接收机内部reciever。
因此,广播接收器从来没有得到正确注册。

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.

要在code注册的话题:

To the topic of registering in code:

这就是呀可能。只要创建你的接收机的一个实例
并使用Context.registerReceiver(mReceiver,新的IntentFilter(...))。

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

如果您在清单登记,也没有必要那样做。
BroadcastReceivers只住的onReceive执行()。因此
系统创建实例,之后杀死他们。

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.

这篇关于检测USB在广播接收器 - 我缺少什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆