简体   繁体   中英

BroadcastReceiver implements LocationListener: How to get context in onLocationChanged

My problem is quite easy: I have a BroadcastReceiver that implements a LocationListener . The LocationListener needs the usual unimplemented methods and those are outside the onReceive of the BroadcastReceiver , so I have no context to use. The thing is that inside the onLocationChanged method (one of the LocationListener unimplemented ones) I have to call a method the must use context and I don't know how to get it.

public class MyBroadcastReceiver extends BroadcastReceiver implements LocationListener {
    @Override
    public void onReceive(Context context, Intent intent) {
    }

    public void onLocationChanged(Location location) {
        method(context);
    }

    public void onStatusChanged(String s, int i, Bundle b) {           
    }

    public void onProviderDisabled(String s) {
    }

    public void onProviderEnabled(String s) {           
    }
}

How can I accomplish this?

You can declare a class level Context like below, and then use it.

public class MyBroadcastReceiver extends BroadcastReceiver implements LocationListener {

private Context context; 
@Override
public void onReceive(Context context, Intent intent) {
this.conext = context;
}

public void onLocationChanged(Location location) {
    method(context);       // Now you can use context
}
public void onStatusChanged(String s, int i, Bundle b) {           
}
public void onProviderDisabled(String s) {
}
public void onProviderEnabled(String s) {           
}

I have a BroadcastReceiver that implements a LocationListener.

If this BroadcastReceiver is registered via the manifest, having it be a LocationListener is pointless, as your process can be terminated milliseconds after onReceive() returns.

I have to call a method the must use context and I don't know how to get it

If you are using registerReceiver() to set up this BroadcastReceiver , and for some reason it makes sense for you to also have it be a LocationListener , your Context is whatever called registerReceiver() ( Activity or 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