我正在尝试为我的android应用程序实现通知,它在除android 9之外的几乎所有版本上都能正常工作(我没有在android 8上进行过检查)。我在androidx上。
public static void openActivityNotification(Context context){
NotificationCompat.Builder nc = new NotificationCompat.Builder(context);
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notifyIntent = new Intent(context, MainActivity.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
nc.setContentIntent(pendingIntent);
nc.setSmallIcon(R.mipmap.ic_launcher);
nc.setAutoCancel(true);
nc.setContentTitle("Notification Demo");
nc.setContentText("Click please");
nm.notify(NOTIFICATION_ID_OPEN_ACTIVITY, nc.build());
}
如何使其在Android 9上运行?
答案 0 :(得分:1)
您似乎缺少了Android O及更高版本所需的通知渠道。 说明文件:https://developer.android.com/training/notify-user/channels 试试这个示例:
private String CHANNEL_ID;
private void createNotificationChannel() {
CharSequence channelName = CHANNEL_ID;
String channelDesc = "channelDesc";
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, channelName, importance);
channel.setDescription(channelDesc);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
assert notificationManager != null;
NotificationChannel currChannel = notificationManager.getNotificationChannel(CHANNEL_ID);
if (currChannel == null)
notificationManager.createNotificationChannel(channel);
}
}
public void createNotification(String message) {
CHANNEL_ID = UiUtil.getStringSafe(R.string.app_name);
if (message != null ) {
createNotificationChannel();
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(UiUtil.getStringSafe(R.string.app_name))
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
Uri uri =RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(uri);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
int notificationId = (int) (System.currentTimeMillis()/4);
notificationManager.notify(notificationId, mBuilder.build());
}
}