Panache Panache - 4 years ago 131
Java Question

StartActivity once user click Allow on Permission Screen

My one activity need Location Permission and I wrote below code to get permission. But in this case user need to click twice to open activity if app does not have location permission initially. Can I make some change so that once user click allow on Permission screen, only then intent fires.

int PERMISSION_ALL = 1;
String[] PERMISSIONS = new String[0];
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
PERMISSIONS = new String[]{
Manifest.permission.ACCESS_FINE_LOCATION};
}

if (!hasPermissions(getApplicationContext(), PERMISSIONS)) {
ActivityCompat.requestPermissions(StartupActivity.this, PERMISSIONS, PERMISSION_ALL);
}

if (hasPermissions(getApplicationContext(), PERMISSIONS)) {
new Thread(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(StartActivity.this, Details.class);
startActivity(intent);
}
}).start();
}

Answer Source

Yes you need to override onRequestPermissionsResult

First on onCreate

int PERMISSION_ALL = 1;
String[] PERMISSIONS = new String[0];
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    PERMISSIONS = new String[]{
            Manifest.permission.ACCESS_FINE_LOCATION};
}

if (!hasPermissions(getApplicationContext(), PERMISSIONS)) {
    ActivityCompat.requestPermissions(StartupActivity.this, PERMISSIONS, PERMISSION_ALL);
}

then Override

  @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == PERMISSION_ALL) {
                Intent intent = new Intent(StartActivity.this,Details.class);
                startActivity(intent);
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download