I can't make my receiver work if the app is not already running (If it's running it works fine)
I have the same problem also with the intent USER_UNLOCKED
I managed to make the receiver work when the app is not running with the BOOT_COMPLETED intent by running in my main activity
override fun onCreate(savedInstanceState: Bundle?) {
...
val pref = getSharedPreferences("allow_notify", MODE_PRIVATE).edit()
pref.apply()
val sp = getSharedPreferences("allow_notify", MODE_PRIVATE)
if (!sp.getBoolean("protected", false)) {
val miuiIntent = Intent().setComponent(
ComponentName(
"com.miui.securitycenter",
"com.miui.permcenter.autostart.AutoStartManagementActivity"
)
)
if (packageManager.resolveActivity(miuiIntent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
startActivity(miuiIntent)
sp.edit().putBoolean("protected", true).apply()
}
}
...
}
Right now my service onCreate is exactly
override fun onCreate() {
super.onCreate()
val filter = IntentFilter(Intent.ACTION_BOOT_COMPLETED)
filter.addAction(Intent.ACTION_USER_PRESENT)
val mReceiver: BroadcastReceiver = StartupReceiver()
registerReceiver(mReceiver, filter)
}
and my receiver is just
class StartupReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
MyService.start(context)
}
}
fun start(context: Context){
val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
for (service in manager.getRunningServices(Int.MAX_VALUE)) {
if (service.service.shortClassName.contains("MyService")) {
return
}
}
Intent(context, MyService::class.java).also {
context.startService(it)
}
}
<receiver
android:name=".StartupReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.USER_PRESENT"/>
</intent-filter>
</receiver>
Add permission in the manifest
NB: From targetSdk 31, Service can be invoked only when the application is in the foreground. You can use the WorkManager to do the intended task instead.