Home > Enterprise >  Android: Start activity from background service
Android: Start activity from background service

Time:09-30

Im curently working on an android app which controls ioT devices like water pumps and other stuff. We would like to implement a feature where the app is able display some sort of alarm (like an incoming call) which the users needs to confirm/dismiss if certain sensor values of devices are under/above specific thresholds (e.g. temperature goes below 0°C) even if the app is suspended, closed or in the background.

I've read about system alert windows and background services but could'nt find anything on how to implement such feature.

https://developer.android.com/guide/components/activities/background-starts

On the webpage above they state that starting activities form the background is very restricted and only possible in very specific situations. So our question is if it's even possible to do and if yes, how or if there are other way's to achive this. Thanks

CodePudding user response:

Yes of course you can achieve that easilly via foreground service in android, but first you have to add permission of Draw over other apps in AndroidManifest.xml and ask permission to a user to give the application this permission, you can do that via this code in your foreground service class which extend service:

if (!Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:"   getPackageName()));
startActivityForResult(intent, 0);

}

to start your activity in your foreground service class, you have to set to your intent object this flag : Intent.FLAG_ACTIVITY_NEW_TASK

CodePudding user response:

If you want to keep your app active in the background, then you should start a Foreground Service. There are already several plugins for this, e.g. https://github.com/capawesome-team/capacitor-android-foreground-service.

To notify the app about certain events I would recommend to use (silent) push notifications.

  • Related