Force application to restart from first Activity (when a permission is denied)

后端 未结 5 1823
庸人自扰
庸人自扰 2021-02-02 09:46

It is known that when we deny permissions at runtime in Android 6.0 and resume the app from the recent menu, the app process

5条回答
  •  南笙
    南笙 (楼主)
    2021-02-02 10:19

    Did u mean this?

    MainActivity:

    public class MainActivity extends AppCompatActivity {
    
    TextView txt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txt = (TextView)findViewById(R.id.txt);
    
        txt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
    
                Intent intent = new Intent(MainActivity.this, ActivityB.class);
                intent.putExtra("from","MainActivity");
                startActivity(intent);
                finish();
            }
        });
    }
    }
    

    ActivityB :

        public class ActivityB extends AppCompatActivity {
    
    String intentTxt="";
    final int MY_PERMISSIONS_REQUEST_PHONE_CALL = 1;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_b);
        intentTxt = getIntent().getStringExtra("from");
    }
    
    
    @Override
    protected void onResume() {
        super.onResume();
        if(intentTxt.equals("MainActivity")) {
            if (ContextCompat.checkSelfPermission(ActivityB.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    
                ActivityCompat.requestPermissions(ActivityB.this, new String[]{android.Manifest.permission.CALL_PHONE},
                        MY_PERMISSIONS_REQUEST_PHONE_CALL);
            }
        }
            intentTxt = "";
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_PHONE_CALL: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "32434"));
                    startActivity(intent);
    
                } else {
    
                    Intent intent = new Intent(ActivityB.this,MainActivity.class);
                    startActivity(intent);
                    finish();
                }
                return;
            }
        }
    }
    }
    

    You can start the splashActivity/HomeActivity from onRequestPermissionsResult of ActivityB.Check for permission in onResume of ActivityB so that the permission dialog appears when the ActivityB is called for the first time and also when resumed.

提交回复
热议问题