當我的警報管理器觸發我的 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);
添加回答
舉報
0/150
提交
取消