『Android』AlarmManager 定時器


定時器,是靠Broadcast接收後去執行方法.
所以要先給他PendingIntent,產生PendingIntent必須要有Intent.
然後必須還有一個BroadcastReceiver.


產生BroadcastReceiver,並且將 REPEAT_ID 寫在AndroidManifest.xml告訴他有這個動作.

 <application
        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.NotificationCB">
        <receiver
            android:name=".MyReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.lihan.notificationcb.MyReceiver.REPEAT_ID"/>
            </intent-filter>

        </receiver>
class MyReceiver : BroadcastReceiver() {
    companion object{
        val REPEAT_ID = "repeat"
        val TAG = MyReceiver::class.java.simpleName
    }
    override fun onReceive(context: Context, intent: Intent) {
        if(intent.action == REPEAT_ID){
            Log.d(TAG, "onReceive: ${intent.action}")
            NotificationSend(context).sendNotification(
                NChannel(
                    "School",
                    "Mr.Bob"
                )
            )
        }
    }
}

產生Intent

MainAcitvity

       val repeatIntent  = Intent(this@MainActivity,MyReceiver::class.java).apply {
            action = MyReceiver.REPEAT_ID
        }

產生PendingIntent

        val repeatPendingIntent = PendingIntent.getBroadcast(this,0,repeatIntent,0)

產生AlarmManager

AlarmManager.RTC表示闹钟在睡眠状态下不可用,该状态下闹钟使用绝对时间,即当前系统时间,状态值为1;
AlarmManager.RTC_WAKEUP表示闹钟在睡眠状态下会唤醒系统并执行提示功能,该状态下闹钟使用绝对时间,状态值为0;
參考:https://www.cnblogs.com/zyw-205520/p/4040923.html


        val alarmManager = (getSystemService(Context.ALARM_SERVICE) as AlarmManager)
        alarmManager.setRepeating(
            AlarmManager.RTC_WAKEUP,
            System.currentTimeMillis(), //啟動App後馬上執行
            5000L, //五秒後重複執行,但最低好像是6分鐘
            repeatPendingIntent
        )
#Android #AlamManager #定時器 #定時 #重複執行 #重複






你可能感興趣的文章

[Note] Node.js + express: Server & Routing

[Note] Node.js + express: Server & Routing

D28_ JS102 + 作業解題

D28_ JS102 + 作業解題

SQL 資料處理

SQL 資料處理






留言討論