无法将ReceiverRestrictedContext强制转换为位置服务的android.app.Activity

时间:2018-08-29 09:04:59

标签: android broadcastreceiver receiver

我正在我想要获取上一个已知位置的接收器上运行,在运行时它给我一个错误:ReceiverRestrictedContext cannot be cast to android.app.Activity 下面提供了我的接收器类,包括清单片段。我只想在接收器类中获取我的最后一个已知位置。我在这里搜索了类似的问题,但没有为我工作。

谢谢

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();
            }

        }
    }
}

1 个答案:

答案 0 :(得分:0)

您只能在“活动”中使用FusedLocationProviderClient

不需要每个上下文都是一个Activity上下文。

像Dialog / Fragment中的getContext()一样,可以强制转换为其父活动。但是不能将广播接收上下文转换为活动上下文。

黑客

  • 创建一个空白的布局活动,从BroadcastReceiver开始该活动,并在该活动中输入您的位置代码。

或者您可以使用服务,您将从BroadcastReveiver启动此定位服务,这里是good example的定位服务。

进一步阅读

What is different between MainActivity.this vs getApplicationContext()