本文介绍了用户在权限屏幕上单击“允许"后,即启动活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一项活动需要位置许可",因此我编写了以下代码来获取许可.但是在这种情况下,如果应用最初没有位置权限,则用户需要单击两次以打开活动.我是否可以进行一些更改,以便一旦用户在权限"屏幕上单击允许",则只会触发意图.

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();
                            }

推荐答案

是的,您需要覆盖onRequestPermissionsResult

首先在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);
}

然后覆盖

  @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);
    }

这篇关于用户在权限屏幕上单击“允许"后,即启动活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 03:18