Android8.0 后台服务保活的一种思路

前端APP 投稿 58400 0 评论

Android8.0 后台服务保活的一种思路

Android8.0 后台服务保活的一种思路 | Stars-One的杂货小窝

项目中有个MQ服务,需要一直连着,接收到消息会发送语音,且手机要在锁屏也要实现此功能

目前是使用广播机制实现,每次MQ收到消息,触发一次启动服务操作逻辑

在Android11版本测试成功,可实现上述功能

步骤

具体流程:

  1. 进入APP

  2. 开启后台服务Service

  3. 后台服务Service开启线程,连接MQ

  4. MQ的消费事件,发送广播

  5. 广播接收器中,处理启动服务(若服务已被关闭)和文本语音播放功能

1.广播注册

<receiver
    android:name=".receiver.MyReceiver"
    android:enabled="true"
    android:exported="true">
</receiver>
public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent {
        String action = intent.getAction(;
        //匹配下之前定义的action
        if ("OPEN_SERVICE".equals(action {
            if (!ServiceUtils.isServiceRunning(MqMsgService.class {
                Log.e("--test", "服务未启动,先启动服务";
                Intent myIntent = new Intent(context, MqMsgService.class;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O {
                    context.startForegroundService(intent;
                } else {
                    context.startService(intent;
                }

            }

            String text = intent.getStringExtra("text";
            Log.e("--test", "广播传的消息"+text;

            EventBus.getDefault(.post(new SpeakEvent(text;
        }
    }
}

语音初始化的相关操作都在服务中进行的,这里不再赘述(通过EventBus转发时间事件)

这里需要注意的是,Android8.0版本,广播不能直接启动服务,而是要通过方法,而调用了方法,则是需要服务在5s内调用一个方法

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O {
    Notification notification = NotifyUtil.sendNotification(this, "平板", "后台MQ服务运行中", NotificationCompat.PRIORITY_HIGH;
    startForeground(1, notification;
}

上面这段代码,就是写在Service中的onCreate方法内,之前也是找到有资料说,需要有通知栏,服务才不会被Android系统给关闭,也不知道有没有起到作用。        

编程笔记 » Android8.0 后台服务保活的一种思路

赞同 (61) or 分享 (0)
游客 发表我的评论   换个身份
取消评论

表情
(0)个小伙伴在吐槽