【问题标题】:Activity not restarting when requesting permission in Android 6.0在 Android 6.0 中请求权限时 Activity 未重新启动
【发布时间】:2016-08-22 12:55:50
【问题描述】:

当我试图请求许可时,请求对话框出现并且背景变黑,无论用户按“允许”或“拒绝”,应用程序正在关闭,而不是像文档中提到的那样重新启动。这是我的代码

if (ActivityCompat.checkSelfPermission(Login_Activity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(Login_Activity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
         ActivityCompat.requestPermissions(Login_Activity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION}, 1);


@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults)
{
    switch (requestCode)
    {
        case 1:
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                //
            }
            else
            {
                //
            }

        break;
    }
}

【问题讨论】:

  • 您在文档中的哪个位置看到该活动应该重新启动?
  • 为什么要投反对票?至少写一个评论,这样我才能理解我做错了什么,这样你就可以否决我的问题
  • 如果应用关闭,可能有错误。请检查 logcat 输出,如果有错误,请发布..
  • logcat 中没有任何错误
  • 听上去真的是崩溃了。或者你有一些代码在阻塞 UI 线程的权限对话框之后运行?

标签: android permissions runtime android-6.0-marshmallow


【解决方案1】:

活动不会重新启动。一旦用户授予权限,您应该在此处调用所需的函数。

在用户响应后,此方法将被调用。

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults)
{
    switch (requestCode)
    {
        case 1:
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                // Here you should call the functions whatever you want 
            }
            else
            {
                //If user didn't provide you permission. You will get this else statement. SO you should omit to call the functions(ex. If you requested for the camera access . You shouldn't call the camera functions after user denying permission. If you do app will crash)
            }

        break;
    }
}

如果你想在用户授权后重新开始上课

Intent intent = getIntent();
finish();
startActivity(intent);

在 if 语句中调用这个函数。

【讨论】:

  • 我不希望我的活动重新开始,你只是复制了我的代码并告诉我答案吗?
  • 阅读评论部分@Haidar
  • 我已经知道 if else 语句的用途,这不是我的问题。我的问题是为什么活动正在重新启动或关闭,我不知道到底发生了什么,也不知道如何收听允许或拒绝的回调。对不起,没有答案
  • 在用户允许您访问之前,不要在 oncreate 中调用请求的权限函数。这就是你遇到问题的原因。 (如果您请求摄像头。您不应该在 oncreate 中调用摄像头函数)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多