繁体   English   中英

在Android中静态注册自定义广播接收器的正确方法是什么?

[英]What is the right way of static registration of custom Broadcast receiver in Android?

我要动态注册接收者,而不是动态注册。 对于动态注册,它运行良好,我正在使用以下代码:

..
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中:

<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)
    {..}
}

首先,清单中不能包含private BroadcastReceiver ,因为Android需要能够创建它的实例。 请将此信息公开。

其次,静态内部类名称的语法为LocationListener$GPSActionReceiver ,而不是LocationListener.GPSActionReceiver

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM