简体   繁体   中英

Android: Start activity from background service

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 (eg 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM