Start App From Service in BackGround in oreo and newer - android

my goal is show an activity in every where(even lock screen) on a specific time.
i could in previous android versions until Oreo do this work , but after Oreo Google change the methods, "if you want to display a view on lockScreen use "Activity.this.setShowWhenLocked(true);" :Google says. then i have to create an activity and only use a service wasn't enough.
My Solution : i use AlarmManger to run a service in background on a specific time, that service start my activity(my goal).
Problem : in previous versions android until Oreo , i don't have problem. app works fine . even that time i close my app from recent app , or phone locked. but in Oreo and newer when app works when it is in foreground.
point : in my intent i use this flag :FLAG_ACTIVITY_NEW_TASK
question : how to run a specific activity from a background service even when app is close or phone locked, in Oreo and newer version?

You can't achieve this desired result using background service instead you must consider Foreground service for this task. Here you can find further details about Foreground Services in Android. docs reference
Hope this will help you.

Pardon, but the question here is how to run an activity or a task even when the app is closed. Foreground service will exist as long as the user is interacting with the app or there is a persistent notification showing the task progress, this isn't a case here.
I'd strongly recommend you to go for the workmanager to perform background task. There is a brilliant codelab on the same here :
https://codelabs.developers.google.com/codelabs/android-workmanager/#0
and read the docs here :
https://developer.android.com/topic/libraries/architecture/workmanager

in addition that works i done previous, i understood MIUI in Xiaomi prevent from displaying pop-up window that comes from back ground , then i got its permission and solved problem, now i can see my view anywhere i want. here is a brief for whom that want :
Permissins :
1.Overlay window
2.pop-up window from background(in Xiaomi and probably Other Chinese Phone UI)
Levels :
set a alarm from Activity with Calendar & PendingIntent in AlarmManger to run my Service in a specific time
when i computed my values in Service then Intent to ActivityViewer, in this step i add FLAG_ACTIVITY_NEW_TASK to my intent(according to google docs in android Pie you have to add this flag to your intent for this usage).
In my ActivityViewer according to google docs , I use Activity.setWhenLock() method to show my view even in lock screen and use TYPE_APPLICATION_OVERLAY for Oreo and newer , and use TYPE_TOAST for version 6 until Oreo , and use TYPE_SYSTEM_ERROR for before 6 , in setLayoutParams for setType.
I use this code for getting pop-up window from background permissin in Xiaomi :
Intent intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
intent.setClassName("com.miui.securitycenter",
"com.miui.permcenter.permissions.PermissionsEditorActivity");
intent.putExtra("extra_pkgname", getPackageName());
startActivity(intent);

Related

How to cancel any/all work manager request if the app is removed directly from app tray?

I'm trying to use Android WorkManager in an application in order to schedule some background task. The requirement is to cancel the API request when the app is removed directly from app-tray.
I'm able to detect if app is getting removed from app-tray, by using Service class -> onTaskRemoved method. And here I'm making the WorkManager API cancel request.
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Log.d("onTaskRemoved","onTaskRemoved called");
WorkManager.getInstance().cancelAllWork();
}
This is working fine as expected. Please suggest if there is any other better alternative to achieve it.
For some android devices (for some vendors) they implemented like if any apps is removed from app tray means they will force stop the app.So the services,work manager are also stopped.
For some other android devices (for some
other vendors) they implemented like if any apps is removed from app tray means they will stop/kill only the current activity of the app & not force stop the app.So the services,work manager are not stopped.
First you need to check your target devices is comes in which category.
If you need to do this, I think you're probably using the wrong tool. WorkManager is specifically for requests that need to persist and execute at some point. Consider using an Executor or coroutine instead.

on android 8, will the background child process get suspended when app has a service and a notification in the foreground?

my app has a proxy server in a native executable written by C, it always runs in the background, let's call it httpproxy.exe.
The main activity I use startForegroundService and startForeground with a persist notification to keep the app in the foreground avoid killing by system, then run the httpproxy.exe in the background.
my app works well on android 5 and older verisons, but on android 8.0, when the activity goes background after minutes, httpproxy.exe looks like getting suspended, so I have to bring my app up time after time, that's unacceptable.
I heard there are a so-called Background Execution Limits on android 8,
how can I have my app normally work like before?
Make sure, that your app is excluded from the Doze mode.
Checking:
PowerManager powerManager =
(PowerManager)getActivity().getSystemService(Activity.POWER_SERVICE);
powerManager.isIgnoringBatteryOptimizations(getActivity().getPackageName());
Asking the user to white-list your app:
Intent intent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
startActivity(intent);

HERE SDK is unusable in background on Android 8

HERE SDK tries to start its MapService internally when consumers call MapEngine.init(). Due to Android 8 background execution restrictions, this fails if MapEngine is to be initialized from a background Service. Is there any way to initialize MapEngine that doesn't involve the SDK starting a Service internally?
The exception log:
> java.lang.IllegalStateException: Not allowed to start service Intent { act=com.here.android.mpa.service.MapService.v3 cmp=de.newecho.app/com.here.android.mpa.service.MapService (has extras) }: app is in background uid UidRecord{6924417 u0a225 CEM idle change:cached procs:1 seq(0,0,0)}
at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1521)
at android.app.ContextImpl.startService(ContextImpl.java:1477)
at android.content.ContextWrapper.startService(ContextWrapper.java:650)
at com.nokia.maps.MapServiceClient.a(SourceFile:77)
at com.nokia.maps.MapsEngine.a(SourceFile:622)
at com.nokia.maps.MapsEngine.a(SourceFile:364)
at com.here.android.mpa.common.MapEngine.init(SourceFile:260)
EDIT:
I have no idea why this got marked as a duplicate. My question is not about how to generally handle background work on Android 8 as in the "duplicated" question. The call to startService() happens in the HERE SDK internally, so consumers have no means to change that. The question is directed towards HERE devs to clarify whether there is a way to initialize MapEngine in a manner so that the HERE SDK doesn't start a Service internally.
Within HERE Mobile SDK it is not possible to init the map from a background thread.
It is possible to continue function like Navigation in background after map init(in foreground) is done by ensuring a) The required map data is already loaded on the device, b) a foreground service is triggered
From Documentation : https://developer.here.com/documentation/android-premium/dev_guide/topics/map-guidance.html
If you are using Turn-by-Turn Navigation Mode
for driving, you can also set HERE SDK to perform guidance (including
voice instructions and event callbacks) while the app is in the
background. However, unlike the foreground navigation scenario, HERE
SDK does not stream map data during background navigation on Android.
To properly support background navigation for these devices, HERE SDK
requires your app to preload map data (such as for the current city or
state) using the MapLoader class.
Important: Starting with Android O (8.0), if your app is running in
the background, then the location system service only computes a new
location for your app a few times each hour. To avoid this behavior,
start a foreground service by following the instructions in the
Android documentation. Important: Starting with Android P (9.0), app
that requires use of foreground service must request
android.permission.FOREGROUND_SERVICE permission from the user. For
more information, please refer to Android Pie behaviour change
documentation.

Avoid Screen Overlay Detected for service that uses SYSTEM_ALERT_WINDOW

My app main usage is overlay, the overlay is running from a service.
Android Security add the nice "Screen Overlay Detected"
I want to avoid "Screen Overlay Detected" when user tries to change permissions. so... I've add an AccessiblityService that detects:
if ( event.getPackageName().equals("com.google.android.packageinstaller") ){
stopService(myServiceIntent);
}
However, even now I see this message popping. (when my service is stopped...).
I saw Twilight does it without problem.
What am I missing?
p.s. - I've also tried building a signed apk but saw exact same behavior.
It seems I've been able to resolve this.
a) stopService isn't assured your service will be stopped.
as described here :
It will not be destroyed until all of these bindings are removed. See > the Service documentation for more details on a service's lifecycle.
b) I was able to kill my service by sending intent that called stopSelf().
However process killing/starting can be slow.
c) Best resolution: so it seems Android checks for view visibility. no need to kill services or do anything more complicated.
Current way I'm doing it:
- AccessibilityService (already used by my app) monitor "com.google.android.packageinstaller" though it can be refined to class: "com.android.packageinstaller.permission.ui.ManagePermissionsActivity"
Once detected in this class, we send Intent to "duck", and when we're out, we send another intent that we're back on.
The service handles those calls by:
[ourView].setVisibility(View.INVISIBLE); // when permission settings shown
[ourView].setVisibility(View.VISIBLE); // when normal flow
As long as Android 6.x is buggy on some devices where this "overlay alert" is displayed without any reason (on 2 to 5% of the devices according to my analytics data), the best solution is to avoid the whole permission process by defining the targetSdk to 22. Take care that you can't downgrade the target sdk for a new version or this will induce a INSTALL_FAILED_PERMISSION_DOWNGRADE error when the user updates requiring an unisntall/install of the app.

PushNotifications and MVVMCross

I have a service which handles my push notification. When the app is running, everything is fine, but once the app is not running I am getting a null reference exception. I have traced it back to the following line :
newIntent = Mvx.Resolve<IMvxAndroidViewModelRequestTranslator> ().GetIntentFor (request);
This line is used to get the intent for the status bar notification so when the user clicked on it it will take him to the appropriate page inside the app. I am pretty sure that This is null because the application is not running and the MvvmCross framework did not have a chance to initialize and register the IMvxAndroidViewModelRequestTranslator.
My question is what should I use as an alternative?
UPDATE
So I dis some reading and I believe that a regular intent wont work and break my app. I was thinking about creating a dummy activity In my app which will get the regular intent I will send and move on to use the IMvxAndroidViewModelRequestTranslator (which should be not null since the app was started) and create an MvvmCross navigation request.
Any thoughts?
UPDATE 2
Tried the approach above with no luck... still failing on the same line...
So basically the question is how can I launch the app from the status bar while making the MvvmCross eco system start as well...
Thanks
Amit
So what I ended up doing is once the notification arrived and the Mvx.Resolve threw an exception I (meaning the app is not running), I saved the notification data to the app preferences and launched the app to its main activity and there I simpley checked for the notification data and if it existed I navigated to the appropriate activity.
When the Android UI starts, then MvvmCross runs Setup to initialise things like IoC, your application, etc
If you need to initialise your MvvmCross application within a non-UI setting, then try the answer from MvvmCross DataService in an Android Broadcast listener which shows how to access the same setup that the UI uses.

Categories

Resources