Any way to link to the Android notification settings for my app?

前端 未结 10 1075
逝去的感伤
逝去的感伤 2020-11-28 03:15

Is there any way I can launch an intent to get to Android\'s notification settings screen for my app (pictured below)? Or an easy way I can make a PreferenceScreen item that

10条回答
  •  清歌不尽
    2020-11-28 03:41

    I'd like to present a clean-code version of @Helix answer:

    fun openNotificationsSettings() {
        val intent = Intent()
        when {
            Build.VERSION.SDK_INT > Build.VERSION_CODES.O -> intent.setOpenSettingsForApiLarger25()
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP -> intent.setOpenSettingsForApiBetween21And25()
            else -> intent.setOpenSettingsForApiLess21()
        }
        app.startActivity(intent)
    }
    
    private fun Intent.setOpenSettingsForApiLarger25(){
        action = Settings.ACTION_APP_NOTIFICATION_SETTINGS
        putExtra("android.provider.extra.APP_PACKAGE", app.packageName)
    }
    
    private fun Intent.setOpenSettingsForApiBetween21And25(){
        action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
        putExtra("app_package", app.packageName)
        putExtra("app_uid", app.applicationInfo?.uid)
    }
    
    private fun Intent.setOpenSettingsForApiLess21(){
        action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
        addCategory(Intent.CATEGORY_DEFAULT)
        data = Uri.parse("package:" + app.packageName)
    }
    

    One can go even further and extract each when branch into a compact class. And create a factory in which when would be.

提交回复
热议问题