【问题标题】:How to pass permissions to Broadcastreceiver?如何将权限传递给 Broadcastreceiver?
【发布时间】:2018-06-17 06:00:30
【问题描述】:

在 MainActivity 中,我的应用获得了ACCESS_FINE_LOCATION 的权限。 然后它设置一个警报

PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 101, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 5000, 5000, pendingIntent);

当 then 接收器被触发时,它没有看到权限被授予:

public class AlarmReceiver extends BroadcastReceiver {

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

    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    Location location;
    if (context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(context, "Granted", Toast.LENGTH_SHORT).show();
        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    }else{
        Toast.makeText(context, "Not Granted!", Toast.LENGTH_SHORT).show();
        return;
    }
}
}

我不希望应用再次向用户请求许可,我该如何实现?

提前感谢您的努力。

【问题讨论】:

    标签: android broadcastreceiver android-permissions


    【解决方案1】:
    if(context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
    

    这行表示权限不是granted。你写错了condition,需要征求许可。你的情况应该是这样的

    if (context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(context, "Not Granted!", Toast.LENGTH_SHORT).show();
            return;
        }else{
    
            Toast.makeText(context, "Granted", Toast.LENGTH_SHORT).show();
            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-12
      • 2019-10-24
      • 1970-01-01
      • 1970-01-01
      • 2017-10-01
      • 2015-01-30
      相关资源
      最近更新 更多