在我的应用程序中,我有一个需要几个权限的后台服务.
由于M OS要求开发人员确保这些权限已在运行时获得批准,因此我尝试使用以下代码检查权限.
getApplicationContext().checkSelfPermission()
对于允许/拒绝,我没有表现出任何恶意.相反,我在“应用程序信息”页面中允许了这些权限(在设置>应用程序>应用程序管理器>我的后台服务中)
但是,尽管我已在“应用程序信息”页面中启用了这些权限,
上面的函数总是返回-1.
如果在应用程序信息页面上更改了权限批准,如何正确检查权限?
解决方法:
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;public boolean checkLocationPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Show an expanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. //Prompt the user once explanation has been shown ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); } return false; } else { return true; }}@OverrIDepublic voID onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_LOCATION: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the // contacts-related task you need to do. buildGoogleapiclient(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Todo: ConsIDer calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overrIDing // public voID onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } mGoogleMap.setMyLocationEnabled(true); } else { // permission denIEd, boo! disable the // functionality that depends on this permission. Toast.makeText(this, "permission denIEd", Toast.LENGTH_LONG).show(); } return; } // other 'case' lines to check for other // permissions this app might request }}
你应该做这样的事情.
总结以上是内存溢出为你收集整理的Android M权限:checkSelfPermission()始终返回-1全部内容,希望文章能够帮你解决Android M权限:checkSelfPermission()始终返回-1所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)