
物联网环境,为了解决不同厂商、不同设备、不同网络情况下使用顺畅,同时也考虑到节约成本,缩小应用体积的好处,我们需要一个服务应用一直存在系统中,保活它以提供服务给其他客户端调用。
开机自启动,通过广播通信,
必要权限
<!--允许查看所有未启动的应用-->
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"
tools:ignore="QueryAllPackagesPermission" />
<!--// 添加接收开机广播的权限-->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<!--前台服务-->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
开机自启动Service相关代码
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Build
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
/**
* @date 2023/2/28
* @email L2279833535@163.com
* @author 小红妹
* @package com.xxx.xxx.receiver
* @describe 接收开机广播、开机自启动Service
* @copyright
*/
class BootBroadcastReceiver : BroadcastReceiver() {
private val ACTION_BOOT = "android.intent.action.BOOT_COMPLETED"
override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.action == ACTION_BOOT) {
GlobalScope.launch(Dispatchers.Main) {
delay(20000L)
val intent = Intent()
intent.component =
ComponentName("com.xxx.xxx.end", "com.xxx.xxx.end.DeviceService")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context?.startForegroundService(intent)
} else {
context?

文章介绍了在物联网环境中,为确保服务在不同设备和网络条件下稳定运行并节约成本,采用开机自启动Service并通过BroadcastReceiver进行通信的方法。详细展示了所需权限设置,如QUERY_ALL_PACKAGES、RECEIVE_BOOT_COMPLETED和FOREGROUND_SERVICE,以及Service和BroadcastReceiver的相关代码实现。同时,提到了Android不同版本下的兼容性问题,如Android8.0后的前台服务要求和Android12的包可见性设置。
最低0.47元/天 解锁文章
1063

被折叠的 条评论
为什么被折叠?



