ntent intent = new Intent(this, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("This is content title")
.setContentText("This is content text")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_launcher))
.setContentIntent(pi)
.build();
startForeground(1, notification);
正常编写代码出现如下错误
android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x40 color=0x00000000 vis=PRIVATE)
解决方法据说
从Android 8.0(API 26)开始,所有的Notification
都要指定Channel
(通道),对于每一个Channel你都可以单独去设置它;比如通知开关、提示音、是否震动或者是重要程度等;这样每个应用程序的通知在用户面前都是透明的。
如果是第一行代码书的前台服务,直接用下面的代码
Intent intent=new Intent(this,MainActivity.class);
PendingIntent pi=PendingIntent.getActivity(this,0,intent,0);
String CHANNEL_ID = "1";
String CHANNEL_Name = "channel_name";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_Name, NotificationManager.IMPORTANCE_HIGH);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
Notification.Builder builder = new Notification.Builder(this,CHANNEL_ID);
builder.setContentTitle("This is content file");
builder.setContentText("This is content text");
builder.setWhen(System.currentTimeMillis());
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher));
builder.setChannelId(CHANNEL_ID);
builder.setContentIntent(pi);
Notification notification = builder.build();
startForeground(1,notification);
以添加铃声为例,代码如下:
首先,创建一个 NotificationChannel:
NotificationManager mNotiManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Uri mUri = Settings.System.DEFAULT_NOTIFICATION_URI;
NotificationChannel mChannel = new NotificationChannel(String id, String name, NotificationManager.IMPORTANCE_LOW);
mChannel.setDescription(String description);
mChannel.setSound(mUri, Notification.AUDIO_ATTRIBUTES_DEFAULT);
mNotiManager.createNotificationChannel(mChannel);
然后,为你的 Notification 设置 Channel:
Notification notification = new Notification.Builder(MainActivity.this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_notify_status)
.setChannelId(String id) //同上 channel id
.build();
Update:
若不想客制化自己的铃声,可以将优先级设置为 IMPORTANCE_DEFAULT,NotificationManagerService 会自动为其添加默认铃声,详见 NotificationManagerService.java
即:
NotificationChannel mChannel = new NotificationChannel(String id, String name, NotificationManager.IMPORTANCE_DEFAULT);
mNotiManager.createNotificationChannel(mChannel);
有关 led 属性个震动,均可使用 NotificationChannel 设置。