admin管理员组文章数量:1389783
My app runs 2 distinct services, one used to scan iBeacons and retrieve their advertised data, the other sync those data on a distant server.
Those services should run all the time on the mobile, and I would like them to start on boot, to prevent any user oversight.
I tried to catch the BOOT_COMPLETED broadcast, but it is restricted to System apps on newer Android versions. Is there a known workaround ?
My app runs 2 distinct services, one used to scan iBeacons and retrieve their advertised data, the other sync those data on a distant server.
Those services should run all the time on the mobile, and I would like them to start on boot, to prevent any user oversight.
I tried to catch the BOOT_COMPLETED broadcast, but it is restricted to System apps on newer Android versions. Is there a known workaround ?
Share Improve this question asked Mar 17 at 8:07 SaphirelSaphirel 4103 silver badges11 bronze badges2 Answers
Reset to default 1I tried to catch the BOOT_COMPLETED broadcast, but it is restricted to System apps on newer Android versions
BOOT_COMPLETED is not restricted to system apps, you are just not allowed to start certain types of services. Your app can receive this broadcast no problem.
Is there a known workaround?
As you can read from the Restrictions on Services and the Restrictions on Boot Completed there are strict rules in place now to prevent apps from starting things on boot and what you are trying to do is even really discouraged by google. You should be using WorkManager for your background work, the idea of a service always running is something that is now heavily discouraged
You can try with this code. combination of this code you can run your services.
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
For boot receiver mention that code in manifest.
<receiver
android:name=".receiver.MultiTaskReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="9999">
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.SCREEN_ON" />
<action android:name="android.intent.action.SCREEN_OFF" />
<action
android:name="android.conn.CONNECTIVITY_CHANGE"
tools:ignore="BatteryLife" />
</intent-filter>
</receiver>
On behalf of *SCREEN_ON* and *SCREEN_OFF* you can run your service when phone has been started.
package com.niit.mdm.receiver
import android.app.ActivityManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.ConnectivityManager
import android.NetworkInfo
import android.os.Build
import android.util.Log
import com.niit.mdm.data.model.ReInstallSharedData
import com.niit.mdm.data.repository.ReInstallRepository
import com.niit.mdm.data.repository.ReInstallRepositoryEntryPoint
import com.niit.mdm.service.ClientService
import com.niit.mdm.utils.objects.Constants.CLIENT_SERVICE_TAG
import dagger.hilt.android.EntryPointAccessors
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class MultiTaskReceiver : HiltBaseBroadcastReceiver() {
var lastConnection = false
// @Inject
// lateinit var workerEnqueue: WorkerEnqueue
//
// @Inject
// lateinit var apkDetailRepository: ApkDetailRepository
override fun onReceive(context: Context, intent: Intent) {
super.onReceive(context, intent)
Log.d(CLIENT_SERVICE_TAG, "BootReceiver triggered: ${intent.action}")
when (intent.action) {
// Intent.ACTION_SCREEN_ON -> {
// Log.d("MyBroadcastReceiver", "Screen ON")
// // Handle screen on
// startMyServiceIfNotRunning(context)
// }
Intent.ACTION_SCREEN_OFF -> {
Log.d("MyBroadcastReceiver", "Screen OFF")
// Handle screen off
}
// Intent.ACTION_BOOT_COMPLETED -> {
// Log.d("MyBroadcastReceiver", "Boot Completed")
// // Handle boot completed
// }
ConnectivityManager.CONNECTIVITY_ACTION, Intent.ACTION_SCREEN_ON, Intent.ACTION_BOOT_COMPLETED-> {
val cm =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork: NetworkInfo? = cm.activeNetworkInfo
val isConnected: Boolean = activeNetwork?.isConnectedOrConnecting == true
Log.d("MyBroadcastReceiver", "Connectivity changed: $isConnected")
startMyServiceIfNotRunning(context)
// Handle connectivity change
if (isConnected){
ReInstallSharedData.sharedMessage = isConnected.toString()
val entryPoint = EntryPointAccessors.fromApplication(context, ReInstallRepositoryEntryPoint::class.java)
val reInstallRepository: ReInstallRepository = entryPoint.getReInstallRepository()
CoroutineScope(Dispatchers.IO).launch {
reInstallRepository.reInstallApkFromLocalDatabase()
}
println("value of ${intent.action} InterNet ==> ${reInstallRepository.getStatusOfWifi()}")
}
}
}
}
private fun startMyServiceIfNotRunning(context: Context) {
Log.d(CLIENT_SERVICE_TAG, "Check service details")
if (!isServiceRunning(context, ClientService::class.java)) {
Log.d(CLIENT_SERVICE_TAG, "Starting service")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(Intent(context, ClientService::class.java))
} else {
context.startService(Intent(context, ClientService::class.java))
}
// val serviceIntent = Intent(context, ClientService::class.java)
// context.startService(serviceIntent)
}else{
Log.d(CLIENT_SERVICE_TAG, "Service already running")
}
}
private fun isServiceRunning(context: Context, serviceClass: Class<out Service>): Boolean {
val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
for (service in activityManager.getRunningServices(Int.MAX_VALUE)) {
if (serviceClass.name == service.service.className) {
return true
}
}
return false
}
}
本文标签: Android 14Launch Service at bootStack Overflow
版权声明:本文标题:Android 14+ - Launch Service at boot - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744573972a2613508.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论