我正在开发Android应用程序,我需要在上传联系人之前询问用户的联系人权限。以下是我用于@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
dX = v.getX() - event.getRawX();
dY = v.getY() - event.getRawY();
lastAction = MotionEvent.ACTION_DOWN;
break;
case MotionEvent.ACTION_MOVE:
//remove this v.setY() line
v.setX(event.getRawX() + dX);
lastAction = MotionEvent.ACTION_MOVE;
break;
case MotionEvent.ACTION_UP:
if (lastAction == MotionEvent.ACTION_DOWN)
Toast.makeText(MainActivity.this, "Clicked!", Toast.LENGTH_SHORT).show();
break;
default:
return false;
}
return true;
}
的联系人权限的代码。
但问题是我需要每次都要求联系人权限,甚至低于Android M。如何申请适用于所有SDK版本的联系人权限?
Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
答案 0 :(得分:1)
创建一个显示权限请求对话框的方法,该对话框始终显示对话框,但仅调用Android M及更高版本上的权限API:
public void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Contacts access needed");
builder.setPositiveButton(android.R.string.ok, null);
builder.setMessage("please confirm Contacts access");
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
// Only call the permission request api on Android M
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSION_REQUEST_CONTACT);
}
}
});
builder.show();
}
然后在Android M及以上版本中,只在需要时调用它,在M下面,总是调用它:
public void askForContactPermission(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CONTACTS)) {
showDialog();
}
}
} else {
showDialog();
}
}