What is the right way of static registration of cu

2019-07-29 21:34发布

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

2条回答
SAY GOODBYE
2楼-- · 2019-07-29 22:18

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.

查看更多
等我变得足够好
3楼-- · 2019-07-29 22:19

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" />
查看更多
登录 后发表回答