简体   繁体   中英

What is the right way of static registration of custom Broadcast receiver in 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) {  ..}

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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