这是尝试创建通知的代码:
NotificationManager notifManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notifManager.cancelAll();
PSTrip activeTrip = getActiveTrip();
Intent intent = new Intent(context, PSNewJourneyActivity.class);
intent.putExtra("id", activeTrip.getId());
intent.putExtra("userid", activeTrip.getOwner().getId() + "");
intent.putExtra("mode", "active");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
playCheckoutSound(context, false);
int iUniqueId = (int) (System.currentTimeMillis() & 0xfffffff);
PendingIntent pIntent = PendingIntent.getActivity(context, iUniqueId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, "general");
mBuilder.setContentTitle(context.getString(R.string.passenger_name)).setContentText(context.getString(R.string.pit, "name")).setSmallIcon(R.drawable.notification_icon);
mBuilder.setContentIntent(pIntent);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(iUniqueId, notification);
如您所见,我选择了通道ID,并为通知选择了唯一的ID,但仍然没有运气。我在这里做错什么了?
我也试过在lopper.getmainlopper中调用这个,不知道它会影响它,但仍然没有运气。
PS:我的应用有一个前台服务,所以它有一个永久的通知,让用户知道我的应用在后台工作。这就是导致问题的原因吗?
编辑:
我以前添加过这个。通知,在答案中找到:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = notificationManager.getNotificationChannel(channelId);
if (notificationChannel == null) {
int importance = NotificationManager.IMPORTANCE_HIGH;
notificationChannel = new NotificationChannel(channelId, channelDescription, importance);
notificationChannel.setLightColor(Color.GREEN);
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
}
我的手机会振动,但仍不显示通知。
SDK版本:
compileSdkVersion 27
buildToolsVersion '27.0.3'
defaultConfig {
minSdkVersion 17
targetSdkVersion 27
}
电话:华为Mate 10 Pro。安卓8.0
logcat向我提出了这个问题:
05-22 12:34:32.916: E/NotificationService(1184): No Channel found for pkg=nl.hgrams.passenger, channelId=general, id=124397682, tag=null, opPkg=nl.hgrams.passenger, callingUid=10233, userId=0, incomingUserId=0, notificationUid=10233, notification=Notification(channel=general pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x10 color=0x00000000 vis=PRIVATE)