在Android中静态注册自定义广播接收器的正确方法是什么? [英] What is the right way of static registration of custom Broadcast receiver in Android?

查看:393
本文介绍了在Android中静态注册自定义广播接收器的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要静态注册接收者,而不是动态注册。
对于动态注册,它很好用,我正在使用它:

Instead of dynamic registration, I want to statically register my receiver. For dynamic registration, it works well, I was using this :

..
static private IntentFilter GPSActionFilter;
..
GPSActionFilter = new IntentFilter("GGPS Service");
context.registerReceiver(GPSActionReceiver, GPSActionFilter);
..
static private BroadcastReceiver GPSActionReceiver = new BroadcastReceiver(){  
    public void onReceive(Context context, Intent intent) {  ..}

对于静态注册,调试器从不使用onReceive函数,我使用的是:

在AndoridManifest中:

In AndoridManifest :

<receiver android:name="LocationListener$GPSActionReceiver" >   
    <intent-filter>
        <action android:name="LocationListener.ACTION_GPS_SERVICE" />
    </intent-filter>
</receiver>

在代码中:

public class LocationListener extends BroadcastReceiver
{
    public static IntentFilter GPSActionFilter;
    public static final String ACTION_GPS_SERVICE = "com.example.LocationListener.GPSActionFilter";
    public static BroadcastReceiver GPSActionReceiver;
    public void onReceive(final Context context, final Intent intent)
    {..}
}


推荐答案

在清单中声明意图过滤器动作时,android:name必须是字符串文字,并且不能从类访问String。另外,我建议您在意图操作之前添加完全限定的程序包名称,即:

When declaring an intent-filter action in the manifest, the android:name must be a string literal and can not access Strings from classes. Also, I recommend you prepend your fully qualified package name to the intent action ie:

public static final String GPS_SERVICE = "com.example.LocationListener.ACTION_GPS_SERVICE"

然后更改

<action android:name="LocationListener.GPS_SERVICE" />

<action android:name="com.example.LocationListener.ACTION_GPS_SERVICE" />

这篇关于在Android中静态注册自定义广播接收器的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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