分享一段Android許可權設定的程式碼

SerBad發表於2020-11-23

檢查是否有通知欄許可權

NotificationManagerCompat.from(context).areNotificationsEnabled()

開啟通知欄許可權設定頁

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings

object NotificationUtil {
    //呼叫該方法獲取是否開啟通知欄許可權
    fun goToNotificationSetting(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //這種方案適用於 API 26, 即8.0(含8.0)以上可以用
            try {
                val intent = Intent()
                intent.action = Settings.ACTION_APP_NOTIFICATION_SETTINGS
                intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
                intent.putExtra(Settings.EXTRA_CHANNEL_ID, context.applicationInfo.uid)
                context.startActivity(intent)
            } catch (e: Exception) {
                toPermissionSetting(context)
            }
        } else {
            toPermissionSetting(context)
        }
    }

    /**
     * 跳轉到許可權設定
     *
     * @param activity
     */
    private fun toPermissionSetting(activity: Context) {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) {
            toSystemConfig(activity)
        } else {
            try {
                toApplicationInfo(activity)
            } catch (e: java.lang.Exception) {
                L.printStackTrace(e)
                toSystemConfig(activity)
            }
        }
    }

    /**
     * 應用資訊介面
     *
     * @param activity
     */
    private fun toApplicationInfo(activity: Context) {
        try {
            val localIntent = Intent()
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            localIntent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
            localIntent.data = Uri.fromParts("package", activity.packageName, null)
            activity.startActivity(localIntent)
        } catch (e: java.lang.Exception) {
            L.printStackTrace(e)
        }
    }

    /**
     * 系統設定介面
     *
     * @param activity
     */
    private fun toSystemConfig(activity: Context) {
        try {
            val intent = Intent(Settings.ACTION_SETTINGS)
            activity.startActivity(intent)
        } catch (e: java.lang.Exception) {
            L.printStackTrace(e)
        }
    }

}

相關文章