[英]Notification is not opening Activity onClick
我的應用程序中有 AlarmNotification,每次出現時我都想單擊它並從后台打開父 Activity/wakeup 應用程序。 為什么它不起作用? 它會在特定時間顯示通知,因此警報部分按預期工作,但它不會在點擊時執行任何操作。
首先我必須創建通知:
private fun createNotification(){
val vibrateFreq = longArrayOf(1000, 1000, 1000, 1000, 1000)
nb = NotificationCompat.Builder(a, channelId)
.setSmallIcon(R.drawable.logo)
.setContentTitle(title)
.setContentText(text)
.setVibrate(vibrateFreq)
.setStyle(NotificationCompat.BigTextStyle().bigText(textLong))
.setAutoCancel(true)
}
然后我需要注冊警報以在特定時間顯示通知:
private fun createAlarm(){
val pInt = app.createAlarmPendingIntent(a, nb)
val cal = Calendar.getInstance()
cal.add(Calendar.MINUTE, delta)
app.aManager.set(AlarmManager.RTC_WAKEUP, cal.timeInMillis, pInt)
}
fun createAlarmPendingIntent(a: Activity, nb: NotificationCompat.Builder?): PendingIntent{
val nInt = Intent(a, AlarmReceiver::class.java)
nInt.putExtra(
AlarmReceiver.NOTIFICATION_ID,
AlarmNotification.NOTIFICATION_NAME
)
nInt.putExtra(AlarmReceiver.NOTIFICATION, nb?.build())
val pInt = PendingIntent.getBroadcast(
a,
0,
nInt,
PendingIntent.FLAG_UPDATE_CURRENT
)
return pInt
}
然后它會觸發BroadcastReceiver
打開通知:
class AlarmReceiver: BroadcastReceiver(){
companion object{
const val NOTIFICATION_ID = "20288855447-99899"
const val NOTIFICATION = "alarmNotify"
}
override fun onReceive(context: Context?, intent: Intent?) {
val notificationManager = context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notification: Notification? = intent?.getParcelableExtra(NOTIFICATION)
val id = intent?.getIntExtra(NOTIFICATION_ID, 0)
id?.let {
notificationManager.notify(id, notification)
}
}
}
首先,您需要聲明一個 Intent,例如:
Intent notificationClickIntent = new Intent("intent_id")
然后你需要像這樣聲明一個 Pending Intent:
PendingIntent pendingIntent = PendingIntent.getActivity(context, REQUEST_CODE, notificationClickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
在您的通知構建器中添加設置 contentIntent:
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(notificationData.getTitle())
.setContentText(notificationData.getBody())
.setPriority(NotificationCompat.PRIORITY_HIGH)
**.setContentIntent(notificationClickPendingIntent)**
.addAction(R.drawable.ic_notification, context.getString(R.string.turn_on_alarms), notificationButtonClickPendingIntent)
.setAutoCancel(true)
在您的清單中聲明您要打開的活動的意圖過濾器(因為我記得我無法使其適用於啟動器活動,也許它可以工作,我只是放棄了)。
<activity
android:name="Activity_name"
android:launchMode="singleTask"
android:screenOrientation="portrait"
android:theme="@style/AppTheme.NoActionBar.LightStatusBar">
<intent-filter>
<action android:name="intent_id" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
最后但同樣重要的是,如果activity沒有打開,通知onClick會觸發onCreate方法,如果它已經打開,會觸發onNewIntent
希望這可以幫助:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.