簡體   English   中英

如何區分通知中單擊了哪個操作?

[英]How can I differentiate which action has been clicked in a notification?

我正在制作和 Android 應用程序,每天多次發送帶有操作的通知,問題是此時用戶單擊哪個操作並不重要,它總是將第一個意圖發送到廣播接收器。

我的代碼:

fun sendNotification(title: String, content: String, tomaID: Int){
    val takeShotIntent = Intent(context, TreatmentBroadcastReceiver::class.java).apply {
        putExtra("TomaID", tomaID)
        putExtra("AcctionToma", 0)

    }
    val takeShotPendingIntent = PendingIntent.getBroadcast(context, NOTIFICACION_ID, takeShotIntent, PendingIntent.FLAG_ONE_SHOT)

    val skipShotIntent = Intent(context, TreatmentBroadcastReceiver::class.java).apply {
        putExtra("TomaID", tomaID)
        putExtra("AcctionToma", 1)

    }
    val skipShotPendingIntent = PendingIntent.getBroadcast(context, NOTIFICACION_ID, skipShotIntent, PendingIntent.FLAG_ONE_SHOT)

    val postPoneShotIntent = Intent(context, TreatmentBroadcastReceiver::class.java).apply {
        putExtra("TomaID", tomaID)
        putExtra("AcctionToma", 2)
    }
    val postPoneShotPendingIntent = PendingIntent.getBroadcast(context, NOTIFICACION_ID, postPoneShotIntent, PendingIntent.FLAG_ONE_SHOT)


    val notifyBuilder = getNotificationBuilder(title,content)
    notifyBuilder.addAction(R.drawable.ic_capsula, context.getString(R.string.tomar), takeShotPendingIntent)
    notifyBuilder.addAction(R.drawable.ic_capsula,context.getString(R.string.saltar), skipShotPendingIntent)
    notifyBuilder.addAction(R.drawable.ic_capsula,context.getString(R.string.posponer), postPoneShotPendingIntent)
    mNotifyManager = context.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
    mNotifyManager.notify(NOTIFICACION_ID, notifyBuilder.build())
}

和廣播接收器類:

class TreatmentBroadcastReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        val idToma = intent.getIntExtra("TomaID", -1)
        val acctionToma = intent.getIntExtra("AcctionToma", -1)
        Log.d("EstasReciviendo", idToma.toString() + " " + acctionToma)

    }
}

我需要發送一個 ID 和一個數字,代表應用程序應根據用戶選擇執行的操作。 ID 發送沒有問題,但正如我上面提到的,無論點擊哪個操作,onReceive 方法中的“AccionToma”始終為 0。

我的 logcat 輸出:

2019-07-21 17:09:10.993 20286-20286/com.kps.spart.moskimedicationreminder D/EstasReciviendo: 1049 0

那么,如何區分單擊了哪個操作?

為您的三個PendingIntent.getBroadcast()調用使用不同的唯一值,而不是NOTIFICACION_ID

就目前而言,您的第二個PendingIntent.getBroadcast()調用替換了第一個調用,第三個PendingIntent.getBroadcast()調用替換了第二個調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM