val future: ListenableFuture<Int> =
PackageManagerCompat.getUnusedAppRestrictionsStatus(context)
future.addListener(
{ onResult(future.get()) },
ContextCompat.getMainExecutor(context)
)
fun onResult(appRestrictionsStatus: Int) {
when (appRestrictionsStatus) {
// Status could not be fetched. Check logs for details.
ERROR -> { }
// Restrictions do not apply to your app on this device.
FEATURE_NOT_AVAILABLE -> { }
// Restrictions have been disabled by the user for your app.
DISABLED -> { }
// If the user doesn't start your app for months, its permissions
// will be revoked and/or it will be hibernated.
// See the API_* constants for details.
API_30_BACKPORT, API_30, API_31 ->
handleRestrictions(appRestrictionsStatus)
}
}
fun handleRestrictions(appRestrictionsStatus: Int) {
// If your app works primarily in the background, you can ask the user
// to disable these restrictions. Check if you have already asked the
// user to disable these restrictions. If not, you can show a message to
// the user explaining why permission auto-reset and Hibernation should be
// disabled. Tell them that they will now be redirected to a page where
// they can disable these features.
Intent intent = IntentCompat.createManageUnusedAppRestrictionsIntent
(context, packageName)
// Must use startActivityForResult(), not startActivity(), even if
// you don't use the result code returned in onActivityResult().
startActivityForResult(intent, REQUEST_CODE)
}
上のロジックは、Android 6.0 から Android 10、および Android 11 以降のデバイスで動作します。この新しい API を使うだけで十分です。つまり、Android 11 の自動リセット API を呼び出す必要はなくなります。