Android无法使用前台服务问题

在阅读《第一行代码》学习前台服务的用法时发现的问题以及解决方案

学习使用前台服务时按照《第一行代码》创建前台服务:

//创建前台服务
Intent 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)
    .setDefaults(NotificationCompat.DEFAULT_ALL)
    .build();
startForeground(1,notification);//让MyService变成前台服务

运行后报错:

android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=0 contentView=null vibrate=default sound=default defaults=0xffffffff flags=0x41 color=0x00000000 vis=PRIVATE)

后来我发现在SDK版本低于26的模拟器上能成功创建前台服务,而版本高于或等于26的模拟器则会报错,通过观察报错后发现需要为notification设置channel,否则无法使用前台服务。最后修改代码为:

//创建前台服务
Intent intent = new Intent(this,MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this,0,intent,0);
NotificationCompat.Builder builder = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
	//如果模拟器SDK版本高于等于26
    NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);//新建NotificationManager用于管理Notification,设置Channel
    NotificationChannel mChannel = new NotificationChannel("q", "aaa", NotificationManager.IMPORTANCE_HIGH);//新建NotificationChannel对象,参数分别为ChannelId、ChannelName和优先级
    manager.createNotificationChannel(mChannel);//使用NotificationManager设置Channel
    builder = new NotificationCompat.Builder(this,"q");//传入ChannelId,绑定Channel
}else{
	//如果模拟器SDK版本低于26
    builder = new NotificationCompat.Builder(this);
}
    builder
        .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)
        .setDefaults(NotificationCompat.DEFAULT_ALL)
        .build();
startForeground(1,builder.getNotification());//让MyService变成前台服务

运行后没有出现报错,成功使用前台服务。

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值