Android8.0 行为变更之 Serivce

1.在我的MyBroadcastReceiver.java中:

        Intent service = new Intent(context, TimerService.class);
	// Android 8.0使用startForegroundService在前台启动新服务
	if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
	   context.startForegroundService(service);
        else
           context.startService(service);

2.在我的TimeService.java中:

    private static final String CHANNEL_ID = "11111";//渠道ID
    private static final String CHANNEL_NAME = "TimerForegroundServiceChannel";  //渠道名称
       
   //在android8.0以上版本,如果您的服务已启动(正在运行startService(Intent)),那么还应使该 
         //服务在前台运行,并在此状态下向用户提供持续显示的通知。
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            @SuppressLint("WrongConstant")
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME,
                    IMPORTANCE);//构造NotificationChannel对象
            NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
            manager.createNotificationChannel(channel);//创建通知渠道
            //在之前创建的渠道上发送一个通知(用CHANNEL_ID与之前创建的渠道关联)
            Notification notification = new Notification.Builder(getApplicationContext(), CHANNEL_ID).build();
            startForeground(1, notification);//将服务置于前台状态
        }

这样就能正常使用服务了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值