1

I am working on Receiver where I want to get Last known location, on run time it is giving me an error : ReceiverRestrictedContext cannot be cast to android.app.Activity My receiver class is given below including my Manifest snippet. I just want to get my Last known location in my receiver class. I searched similar question here but didn't worked for me.

Thanks

public class AlarmReceiver extends BroadcastReceiver {

    int hour=6;
    int minutes=19;
    Context contextGlobal;
    private FusedLocationProviderClient mFusedLocationClient;

    @Override
    public void onReceive(final Context context, Intent intent) {

        Calendar rightNow = Calendar.getInstance();
        hour    = rightNow.get(Calendar.HOUR_OF_DAY);
        minutes = rightNow.get(Calendar.MINUTE);
        contextGlobal = context;

        final ParseUser pUser = ParseUser.getCurrentUser();

        if(pUser!=null){
            try {
                mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
                mFusedLocationClient.getLastLocation().addOnSuccessListener((Activity)context, new OnSuccessListener<Location>() {
                    @Override
                    public void onSuccess(Location location) {
                        if (location != null) {
                            Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                v.vibrate(VibrationEffect.createOneShot(500,VibrationEffect.DEFAULT_AMPLITUDE));
                            }else{
                                v.vibrate(500);
                            }


                        }
                        Toast.makeText(context,location.getLatitude()+"",Toast.LENGTH_LONG).show();

                    }
                });

            }catch (SecurityException sexp){
                sexp.getMessage();
            }

        }
    }
}
Usman Khan
  • 3,739
  • 6
  • 41
  • 89

1 Answers1

0

You can use FusedLocationProviderClient in Activity only.

Every context is not needed to be an Activity context.

Like getContext() inside Dialog/ Fragment can be cast to its parent Activity. But Broadcast Reveiver context can not be casted to Activity context.

An Hack

  • Create a blank layout activity, start this activity from BroadcastReceiver and do your location code inside this activity.

Or you can use a Service, you will start this location service from BroadcastReveiver, here is an good example of location service.

Further reading

What is different between MainActivity.this vs getApplicationContext()

Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212
  • thanks for your message here. Can you please guide me if I want to get location in my Receiver service, for that how can I do it? – Usman Khan Aug 29 '18 at 09:21