【发布时间】:2017-09-14 10:43:53
【问题描述】:
我正在创建一个需要 READ_CONTACT 和 CALL_PHONE 权限的简单应用程序。我写了下面的代码。
安装后应用程序像这样询问权限 3 次 -
1 of 2 read contacts
2 of 2 call and manage phone
1 of 2 read contacts
2 of 2 call and manage phone
1 of 2 read contacts
2 of 2 call and manage phone
在授予这些权限后,应用程序也无法打开。但是当我再次打开应用程序时,它可以正常工作并且不会再次询问权限。
我有以下代码
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case MULTIPLE_REQUESTS: {
if (grantResults.length > 0) {
boolean contactPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean phonePermission = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (contactPermission && phonePermission) {
// write your logic here
} else {
Toast.makeText(this, "Read Contact & Call phone permissions are required", Toast.LENGTH_SHORT).show();
closeNow();
}
}
break;
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
+ ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale
(this, Manifest.permission.READ_CONTACTS) ||
ActivityCompat.shouldShowRequestPermissionRationale
(this, Manifest.permission.CALL_PHONE)) {
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.CALL_PHONE},
MULTIPLE_REQUESTS);
}
}
setContentView(R.layout.activity_contact_app_bar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
}
【问题讨论】:
-
在
OnCreate中请求权限可能不是一个好主意。活动尚未开始。 -
那么什么时候请求权限呢?
-
理想情况下,在您需要使用您请求的权限之前,但至少在您的活动开始时(
OnResume之后)
标签: java android permissions