如何将权限传递给 Broadcastreceiver?
Posted
技术标签:
【中文标题】如何将权限传递给 Broadcastreceiver?【英文标题】:How to pass permissions to 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;
我不希望应用再次向用户请求许可,我该如何实现?
提前感谢您的努力。
【问题讨论】:
【参考方案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);
【讨论】:
以上是关于如何将权限传递给 Broadcastreceiver?的主要内容,如果未能解决你的问题,请参考以下文章
类型提示。如何暗示传递给函数的对象必须具有某种方法/属性访问权限?
AWS - 如何使用 CDK/CloudFormation 将服务链接角色传递给自动缩放组?
如何将变量传递给 azure devops 管道中的 SqlAzureDacpacDeployment@1 任务