Here I gave one example of never ending application, which, unfortunately, after latest Huwaei update on my phone is not working. I gonna leave that article as is, and here I will show another possible example using mix of my
original article and
this and
this answer.
I have added Service and BroadcastReceiver, in Manifest I have added permissions:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
Then in the MainActivity I have added the method "checkOptimization" and "openBatteryOptimization ":
@SuppressLint("NewApi", "BatteryLife")
private fun checkOptimization(context: Context) {
val packageName = applicationContext.packageName
val pm = applicationContext.getSystemService(POWER_SERVICE) as PowerManager
if (!pm.isIgnoringBatteryOptimizations(packageName)) {
val intent = Intent()
intent.action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
intent.data = Uri.parse("package:" + context.packageName)
context.startActivity(intent)
}
}
fun openBatteryOptimization(context: Context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val intent = Intent()
intent.action = Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS
context.startActivity(intent)
} else {
//Timber.d("Battery optimization not necessary")
}
}
Both methods "checkOptimization" and "openBatteryOptimization" I have added to "onCreate" of MainActivity. For
Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS
In import list I have added:
import android.provider.Settings
import android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
In Gradle I added:
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.1"
Service and receiver first I have copied from original article, then I have added following methods:
private val wakeLock: PowerManager.WakeLock by lazy {
(getSystemService(Context.POWER_SERVICE) as PowerManager).run {
newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "neverEndingApplication:ServiceWakelock")
}
}
private fun acquireWakelock() {
try {
wakeLock.let {
wakeLock.setReferenceCounted(false)
if (!wakeLock.isHeld) {
wakeLock.acquire()
}
}
} catch (e: RuntimeException) {
}
}
private fun releaseWakelock() {
try {
wakeLock.let {
if (it.isHeld) {
it.release()
}
}
} catch (e: RuntimeException) {
}
}
Still in Service I have added acquireWakelock in onCreate:
override fun onCreate() {
super.onCreate()
acquireWakelock()
}
releaseWakelock() I have added when I want to stop the app:
if (intent?.action.equals("stopForeground")) {
job?.cancel()
releaseWakelock()
stopForeground(true)
stopSelfResult(startId)
}
MainActivity I also copied from my
original article.
Example download from
here.