当我的警报管理器触发我的 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
提交
取消