Android: запрос пользовательского разрешения во время выполнения

Кто-нибудь может дать некоторое представление о том, как запрашивать пользовательские пользовательские разрешения на выполнение в Android Marshmallow? Я работаю с провайдером нестандартного контента, у которого есть разрешение на чтение, а другое приложение пытается получить доступ к данным с помощью провайдера нестандартного контента.

2 ответа

Я лично предпочитаю использовать библиотеку разрешений. Вместо большого стандартного кода они, как правило, эффективны, а код очень точен

См. Этот https://github.com/hotchemi/PermissionsDispatcher

@RuntimePermissions
public class MainActivity extends AppCompatActivity {
     //sepcify permissions here
    @NeedsPermission(Manifest.permission.CAMERA)
    void showCamera() {
        //work after permission is granted
    }

    @OnShowRationale({Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS})
    void showRationaleForCamera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
            .setMessage(R.string.permission_camera_rationale)
            .setPositiveButton(R.string.button_allow, (dialog, button) -> request.proceed())
            .setNegativeButton(R.string.button_deny, (dialog, button) -> request.cancel())
            .show();
    }

    @OnPermissionDenied({Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS})
    void showDeniedForCamera() {
        //works when permissions denied
        Toast.makeText(this, R.string.permission_camera_denied, Toast.LENGTH_SHORT).show();
    }

    @OnNeverAskAgain({Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS})
    void showNeverAskForCamera() {
        Toast.makeText(this, R.string.permission_camera_neverask, Toast.LENGTH_SHORT).show();
    }
}

Меня устраивает.

public class MainActivity extends AppCompatActivity {
private static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;

private boolean checkAndRequestPermissions() {
    Context context=getApplicationContext();
    int locationpermission = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION);
    int readphonestatepermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE);
    int permissionSendMessage = ContextCompat.checkSelfPermission(context,Manifest.permission.SEND_SMS);
    int writepermission = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    int readexternalstoragepermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);


    List<String> listPermissionsNeeded = new ArrayList<>();

    if (locationpermission != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
    }

    if (readphonestatepermission != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE);
    }
    if (permissionSendMessage != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.SEND_SMS);
    }

    if (writepermission != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    if (readexternalstoragepermission != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    if (!listPermissionsNeeded.isEmpty()) {
        requestPermissions(listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
        return false;
    }
    return true;
}



@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);


    if (requestCode == REQUEST_ID_MULTIPLE_PERMISSIONS) {



        if (grantResults.length > 0) {
            for (int i = 0; i < permissions.length; i++) {


                if (permissions[i].equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Log.e("msg", "location granted");


                    }
                } else if (permissions[i].equals(Manifest.permission.READ_PHONE_STATE)) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Log.e("msg", "read phone state granted");


                    }
                } else if (permissions[i].equals(Manifest.permission.SEND_SMS)) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Log.e("msg", "sms granted");


                    }

                }else if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Log.e("msg", "write external granted");


                    }
                }else if (permissions[i].equals(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Log.e("msg", "read external storage granted");

                        Toast.makeText(SplashActivity.this, "Please Restart the Application....... ", Toast.LENGTH_LONG).show();
                    }
                }else if (permissions[i].equals(Manifest.permission.READ_LOGS)) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Log.e("msg", "read logs granted");



                    }
                }


            }

        }


    }
}
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle v) {
    // TODO Auto-generated method stub
    super.onCreate(v);
    setContentView(R.layout.activity_splash);


    if (checkAndRequestPermissions()) {

        Toast.makeText(MainActivity.this, "Granted all permissions", Toast.LENGTH_SHORT).show();


    }
}
}