简体   繁体   中英

Android Context Issue - What context should be used in a Broadcast Receiver (Alarm Manager)?

What context should be used in a Broadcast Receiver (Alarm Manager)?

I've tries using this code successfully within a service, but when I try to run it in an AlarmService I get errors in getApplicationContext() and myLocation.getLocation(this, locationResult);

I've tried passing the context that worked in the service of which eliminated the errors, but the program would crash when it ran.

LocationResult locationResult = new LocationResult(){
            @Override
            public void gotLocation(Location location){
                Toast.makeText(getApplicationContext(), "Latitude: "+location.getLatitude()+"\n Longitude: "+location.getLongitude() , Toast.LENGTH_SHORT).show();
            }
        };
        MyLocation myLocation = new MyLocation();
        myLocation.getLocation(this, locationResult);

Errors:

The Toast:

The method getApplicationContext() is undefined for the type new MyLocation.LocationResult(){}

The method getLocation(Context, MyLocation.LocationResult) in the type MyLocation is not applicable for the arguments (Alarm, MyLocation.LocationResult)

You may be keeping this function in a separate class file other than MainActivity.

You can solve this by doing

public static Context context = getApplicationContext();

in your Mainactivity class while defining member variables. Then you can use the context in your toast message in the locationresult class as follows

  Toast.makeText(MainActivity.context, "Latitude: "+location.getLatitude()+"\n Longitude: "+location.getLongitude() , Toast.LENGTH_SHORT).show();

EDIT:

1) A better way would be to pass the context as a parameter from the Activity where you initialize your location class.

2) If you are using the current method, do add a null-check for the context before showing toast message, to eliminate possiblities of null exception.

You should have something like:

public class YourApp extends Application {
        private static YourApp sInstance;
        public YourApp() {
            super();
            sInstance = this;
        } 
        public static YourApp getInstance() {
        return sInstance;
       }
}

Then from your code you can always do

YourApp.getInstance() -> this is your Application Context.

That is the correct way to do it.

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