Request to remove background restriction for the app ( Android )

Viewed 489

If my app is background restricted, how is it possible to request the user to remove the restriction? Is it possible to navigate the user directly to the settings, where he/she can disable the restriction with one click?

ActivityManager activityManager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
if(activityManager.isBackgroundRestricted()) {
    // ??
}   
2 Answers

Also you can send user to general app settings using

val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", packageName, null))
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        startActivity(intent)

Also, background restriction is coupled with battery optimization. So if you will ask user to ignore battery optimization, it will be harder for him to put restriction afterwards.

private fun checkBatteryOptimization() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        val packageName = packageName
        val pm = getSystemService(POWER_SERVICE) as PowerManager
        if (!pm.isIgnoringBatteryOptimizations(packageName)) {
            showBatteryOptimizationDialog()
        }
    }
}

@SuppressLint("BatteryLife")
@RequiresApi(api = Build.VERSION_CODES.M)
private fun requestIgnoreBatteryOptimization() {
    val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
    intent.data = Uri.parse("package:$packageName")
    startActivityForResult(intent, REQUEST_BATTERY_PERMISSION)
}

I was struggling too to find a "clean" solution to this, but the best idea i had was to show an alertdialog for the users to disable the restrictions by redirecting them to the app settings:

 startActivity(
     Intent(
       Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
       Uri.parse("package:${applicationContext.packageName}")
     )
 )

every android manufacturer os has slightly different settings, so its almost impossible to find a common solution for everyone

Related