android - 设备锁定时出现权限对话框

标签 android kotlin android-permissions

当我在 Android 中请求运行时权限时,会出现权限对话框。在这个阶段,如果我锁定设备并再次解锁手机,锁定屏幕上会出现警报对话框。在我按下接受或拒绝之前,它不会去。
我们有什么可以避免这种行为的吗?

enter image description here

最佳答案

故事
这是我在调查此问题后发现的:
当应用调用Activity.requestPermissions(String[], int) , source code对于这种方法。

public final void requestPermissions(@NonNull String[] permissions, int requestCode) {
    if (requestCode < 0) {
        throw new IllegalArgumentException("requestCode should be >= 0");
    }
    if (mHasCurrentPermissionsRequest) {
        Log.w(TAG, "Can request only one set of permissions at a time");
        // Dispatch the callback with empty arrays which means a cancellation.
        onRequestPermissionsResult(requestCode, new String[0], new int[0]);
        return;
    }
    Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
    startActivityForResult(REQUEST_PERMISSIONS_WHO_PREFIX, intent, requestCode, null);
    mHasCurrentPermissionsRequest = true;
}
正如我们所看到的,系统开始了一个新的 Activity 。
startActivityForResult(REQUEST_PERMISSIONS_WHO_PREFIX, intent, requestCode, null);
我追踪到源代码并发现 Activity 是GrantPermissionsActivity .它负责显示权限对话框并处理允许/拒绝/不再询问等事件。
根据该提示,我使用以下 adb 命令查看 Activity 信息。

adb shell dumpsys activity activities


调用前requestPermissions()
Running activities (most recent first):
  TaskRecord{e04b922d0 #1441 A=com.example.myapplication U=0 StackId=1 sz=1}
    Run #0: ActivityRecord{ca6ffc3 u0 com.example.myapplication/.MainActivity t1441}

mResumedActivity: ActivityRecord{ca6ffc3 u0 com.example.myapplication/.MainActivity t1441}
调用requestPermissions()
Running activities (most recent first):
  TaskRecord{e04b922d0 #1441 A=com.example.myapplication U=0 StackId=1 sz=2}
    Run #1: ActivityRecord{bb1aed2 u0 com.google.android.packageinstaller/com.android.packageinstaller.permission.ui.GrantPermissionsActivity t1441}
    Run #0: ActivityRecord{ca6ffc3 u0 com.example.myapplication/.MainActivity t1441}

mResumedActivity: ActivityRecord{bb1aed2 u0 com.google.android.packageinstaller/com.android.packageinstaller.permission.ui.GrantPermissionsActivity t1441}
mLastPausedActivity: ActivityRecord{ca6ffc3 u0 com.example.myapplication/.MainActivity t1441}
解决方案
我认为这是解决问题的流程:
  • 当权限 Activity 显示时,如果用户按下电源键,我们会记住应用程序完成权限 Activity 的 Action ,并通过组合Intent.FLAG_ACTIVITY_CLEAR_TOP将权限 Activity 从Back Stack弹出。和 Intent.FLAG_ACTIVITY_SINGLE_TOP .
  • 用户解锁手机后,我们检查之前的权限 Activity 是否完成,然后我们会再次显示权限 Activity (当用户离开 Activity 时恢复最后的状态)。

  • 实现
    因为应用程序无法检测到用户使用 Activity.onKeyDown(KeyEvent) 按下电源键和 KeyEvent.KEYCODE_POWER ,所以我们将使用 Intent.ACTION_SCREEN_ONIntent.ACTION_SCREEN_OFF反而。
    第 1 步。我的应用程序.java
    public class MyApplication extends Application {
    
        private boolean isScreenOn = false;
    
        private final BroadcastReceiver screenStateReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                isScreenOn = intent.getAction().equals(Intent.ACTION_SCREEN_ON);
            }
        };
    
        @Override
        public void onCreate() {
            super.onCreate();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(Intent.ACTION_SCREEN_ON);
            intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
            registerReceiver(screenStateReceiver, intentFilter);
        }
    
        public boolean isScreenOn() {
            return isScreenOn;
        }
    }
    
    第 2 步。 activity_main.xml
    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <Button
            android:layout_gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="showMyLocation"
            android:text="Show My Location" />
    
    </FrameLayout>
    
    第三步。 MainActivity.java
    public class MainActivity extends AppCompatActivity {
    
        // When the permission dialog is showing, if users press the Power Key
        // to lock the phone, then the onStop() of this activity will be called first,
        // then the system will send a broadcast with Intent.ACTION_SCREEN_OFF action.
        // The duration between 2 events is under 1 seconds.
        private static final long TIMEOUT_MS = 1000;
    
        // When onNewIntent() is called, we use this extra key to distinct with another events
        // which might invoke this method.
        private static final String EXTRA_IS_PERMISSION_DIALOG_DISMISS_WHEN_SCREEN_OF =
                "EXTRA_IS_PERMISSION_DIALOG_DISMISS_WHEN_SCREEN_OF";
    
        // Your location request information.
        private static final int LOCATION_REQUEST_CODE = 100;
        private static final String[] locationPermission = {Manifest.permission.ACCESS_FINE_LOCATION};
        private boolean isPermissionDialogShowing = false;
    
        private final Handler mainHandler = new Handler(Looper.getMainLooper());
    
        // Check whether permission activity is finished when screen off.
        boolean isPermissionActivityFinishedWhenScreenOff = false;
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        @Override
        protected void onNewIntent(Intent intent) {
            super.onNewIntent(intent);
            Bundle data = intent.getExtras();
            if (data != null && data.containsKey(EXTRA_IS_PERMISSION_DIALOG_DISMISS_WHEN_SCREEN_OF)) {
                isPermissionActivityFinishedWhenScreenOff = true;
            }
        }
    
        @Override
        protected void onResume() {
            super.onResume();
    
            // Show the permission dialog again if we dismiss it when screen off before.
            MyApplication myApplication = (MyApplication) getApplication();
            if (myApplication.isScreenOn() && isPermissionActivityFinishedWhenScreenOff) {
                isPermissionActivityFinishedWhenScreenOff = false;
                isPermissionDialogShowing = true;
                requestPermissions(locationPermission, LOCATION_REQUEST_CODE);
            }
        }
    
        @Override
        protected void onStop() {
            super.onStop();
    
            if (!isPermissionActivityFinishedWhenScreenOff) {
                mainHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // Because the permission activity is on the top of this activity,
                        // so we will use Intent.FLAG_ACTIVITY_CLEAR_TOP combine with
                        // Intent.FLAG_ACTIVITY_SINGLE_TOP to finish the permission activity.
                        MyApplication myApplication = (MyApplication) getApplication();
                        if (!myApplication.isScreenOn() && isPermissionDialogShowing) {
                            Intent i = new Intent(MainActivity.this, MainActivity.class);
                            i.putExtra(EXTRA_IS_PERMISSION_DIALOG_DISMISS_WHEN_SCREEN_OF, true);
                            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                            startActivity(i);
                        }
                    }
                }, TIMEOUT_MS);
            }
        }
    
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                               @NonNull int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            isPermissionDialogShowing = false;
        }
    
        // User click on this button to show my location on the map for example.
        // This method is just for testing.
        public void showMyLocation(View view) {
            if (checkSelfPermission(locationPermission[0]) != PackageManager.PERMISSION_GRANTED) {
                isPermissionDialogShowing = true;
                requestPermissions(locationPermission, LOCATION_REQUEST_CODE);
            }
        }
    }
    
    第 4 步。 AndroidManifest.xml
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.myapplication">
    
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    
        <application
            android:name=".MyApplication"
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/Theme.MyApplication">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    
    </manifest>
    

    关于android - 设备锁定时出现权限对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57250953/

    相关文章:

    java - 如何根据日期输入(edittext)查看数据?

    android - 如何在 Flutter 上选择唯一的前置摄像头

    android - 为什么在部署 Android 应用程序时 xalan.jar 崩溃 eclipse

    android - 在 Kotlin 中使用静态 Java 方法作为静态(或单例)属性

    java - 绘制叠加权限仅在首次安装应用程序时询问

    java - 有没有办法从操作系统访问(读/写)特定应用程序的 sqlite 数据库?

    java - Android/Java/Kotlin : Merge 2 Bitmaps in one Canvas

    algorithm - 如何不在 Kotlin 中越界?

    Android onRequestPermissionsResult 未在 fragment 中调用

    android - Google Play 评论 : unable to verify declared functionality CALLER_ID_DETECTION_BLOCKING