什么是Android的定制广播接收器的静态注册的正确方法吗?(What is the right w

2019-10-18 04:04发布

相反,动态注册的,我想静态注册我的接收器。 对于动态注册,它工作得很好,我用的是这样的:

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

Answer 1:

当宣布在清单意向筛选器操作,在android:名称必须是一个字符串文字,不能从类访问字符串。 另外,我建议你在前面加上你的完全合格的包名的意图行动,即:

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


Answer 2:

首先,你不能有一个private BroadcastReceiver在清单中,由于Android需要能够创建它的一个实例。 请你把这个公开。

二,静态内部类的名称语法是LocationListener$GPSActionReceiver ,不LocationListener.GPSActionReceiver



文章来源: What is the right way of static registration of custom Broadcast receiver in Android?