亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

當我的警報觸發 onReceive() 時未顯示通知

當我的警報觸發 onReceive() 時未顯示通知

慕絲7291255 2021-08-25 10:27:24
當我的警報管理器觸發我的 onReceive() 方法時,我試圖彈出一個通知。這就是我所做的@Overridepublic void onReceive(Context context, Intent intent) {    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");    //Acquire the lock    wl.acquire(10000);    startNotification(context);    wl.release();}public void setAlarm(Context context){    AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);    Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);    intent.putExtra(Activity, "MainActivity.class");    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);    assert am != null;    am.set(AlarmManager.RTC_WAKEUP, 60000, pi);}private void startNotification(Context context){    // Sets an ID for the notification    int mNotificationId = 001;    NotificationManager notificationManager;    NotificationCompat.Builder mBuilder;            // Build Notification , setOngoing keeps the notification always in status bar    mBuilder =            new NotificationCompat.Builder(context)                    .setSmallIcon(R.drawable.ic_launcher_foreground)                    .setContentTitle("RandomTitle")                    .setContentText("RandomText")                    .setOngoing(true);    // Create pending intent, mention the Activity which needs to be    //triggered when user clicks on notification(StopScript.class in this case)    Intent notificationIntent = new Intent(context, MainActivity.class);    notificationIntent.putExtra("extra","Extra Notificacion");    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |            Intent.FLAG_ACTIVITY_SINGLE_TOP);    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent , PendingIntent.FLAG_UPDATE_CURRENT);我真的很困惑為什么這個通知沒有顯示,我已經測試了我的警報,它在創建 1 分鐘后觸發,但通知仍然沒有顯示。有任何想法嗎?
查看完整描述

2 回答

?
浮云間

TA貢獻1829條經驗 獲得超4個贊

來自安卓開發者:


當您面向 Android 8.0(API 級別 26)時,您必須實現一個或多個通知渠道。如果您的 targetSdkVersion 設置為 25 或更低,當您的應用在 Android 8.0(API 級別 26)或更高版本上運行時,它的行為與在運行 Android 7.1(API 級別 25)或更低版本的設備上的行為相同。


因為你targetSdkVersion是 28,所以你也必須channelId在Builder構造函數中添加。


將您的代碼更改為:


// Build Notification , setOngoing keeps the notification always in status bar

mBuilder = new NotificationCompat.Builder(context, "notify_001") // Add channel ID to the constructor.

        .setSmallIcon(R.drawable.ic_launcher_foreground)

        .setContentTitle("RandomTitle")

        .setContentText("RandomText")

        .setOngoing(true);


查看完整回答
反對 回復 2021-08-25
  • 2 回答
  • 0 關注
  • 179 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號