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

穿精又带淫゛_ 提交于 2019-12-11 04:35:49

问题


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

For static registration, debugger never hits the onReceive function, I am using this:

In AndoridManifest :

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

In code :

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

回答1:


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"

Then change

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

To

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



回答2:


First, you cannot have a private BroadcastReceiver in the manifest, as Android needs to be able to create an instance of it. Please make this public.

Second, the syntax for the name of static inner classes is LocationListener$GPSActionReceiver, not LocationListener.GPSActionReceiver.



来源:https://stackoverflow.com/questions/16701940/what-is-the-right-way-of-static-registration-of-custom-broadcast-receiver-in-and

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