Background Service Stop when removing app from recent - android

Background service is stop, when removing my app from recent in oppo & vivo mobiles, & Broadcast reciever also not working in that case.

I had same issue with Oppo, Vivo, Mi and etc phones,
after removing from recent applications app was getting killed even services was getting killed
Solution: I had add autostart permissions like this in my application and it worked.
After resolving this issue my app was getting frozen/killed after sometime running in background due to DOZE mode
Solution: for this condition this worked and now my app is working in background in any device
After above things do this:
intent.setClassName("com.coloros.oppoguardelf", "com.coloros.powermanager.fuelgaue.PowerConsumptionActivity");
startActivity(intent);
call above intent, it will redirect you to battery option, "Disable Background Freeze, Abnormal Apps Optimization and Doze from \"Energy Saver ->youAPP"
Note: Once you call above intent, there you may get different options to turn off Battery saving options.

Yes, You have to return START_STICKY;
Please refer this link :
https://www.tutorialspoint.com/android/android_services.htm
example :
public class MyService extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}

You need to ask your users to whitelist your app in their settings for it to work in these phones. The custom OS on these phones only allows whitelisted apps like whatsapp,fb etc to work in background, other apps have to whitelisted manually from settings

yes.
if you want the service to start over you need to configure it as 'sticky':
https://developer.android.com/reference/android/app/Service.html#START_STICKY
After doing this, follow the accepted answer, it will work.

Related

How to handle services that run as foreground when an app is cleared from recent?

My Android app is playing audio while the app runs in the background with a service that runs as foreground, similar to many other apps such as Google Play Music, Spotify, and other music players / podcast player apps.
Most apps I checked, including Google Play Music, will leave the service running even when the app is cleared from recent. On the other hand, some will stop the audio and close the service (I only found Spotify doing that).
I am wondering what is the right way to handle this? Although most apps leave the service open, it seems that users will expect the audio to stop and the notification to disappear from the status bar together with the app.
Is there a right way here?
You can check this link to see what happens to the process when app is removed from
recents list.
Even if onTaskRemoved() is called, the app is not killed in this case. The service continues to exist. It can be proven by going to the hidden developer menu to check running processes.
You can execute some codes in this callback method, and get the desired behaviour.
Since it's a question of opinion, I'm going to give my own as a developer but also a power smartphone user (well, who isn't nowadays):
tl;dr: leave it running
===============================
longer version
The point of using your phone as a music player, is providing you with audio while you're doing other activities, like running, browsing, texting, or even playing music for others connected through a speaker, being the "dj" of your group. You would rarely use a music player as a primary task and I would expect to do that when you're doing something like trying to figure out the lyrics, or watch the videoclip (and hence, you would use YouTube). Thus, it is my belief that your music player should have a separate lifecycle than the rest of your phone activities. Imagine the nightmare of playing music for others and music suddenly stops while you're messing with unrelated stuff on your phone.
However, you have a point when mentioning that "it seems that users will expect the audio to stop and the notification to disappear from the status bar together with the app". I wouldn't get the whole statement as true, rather extract the gist: users want to stop their music app easily.
In that sense, you should make it as easy as possible to stop playback to optimize your user experience. Out of the top of my head, I would imagine the best way of doing that would be a nice "X" button in your notification extended (or even when compact) version. The user then can stop the playback right from the status bar and not have to go through bringing the app to the front.
If you do want to go a step further, you could have an option in your settings to either use a foreground or background service -to make it easier for the user to understand, you could use wording like "stop music when recent apps are cleared", hence delegating the choice to your user, according to their needs. That, of course, would add complexity and too much power to your users so it's up to you to figure out if you need it.
Leave it running, with a notification.
It's all in the name.
According to Android Developers,
"The Recents screen (also referred to as the Overview screen, recent
task list, or recent apps) is a system-level UI that lists recently
accessed activities and tasks."
Swiping the task away from this list just removes it from the list, not from execution.
Notifications (Certainly under Oreo) are where you let your user know that you still have service(s) running. Use the notification to allow them to re-open the task, and then terminate the service as they see fit.
You are making like music player application, so most of the time user expected that music will be played even if the application is closed from the recent task. Now you are using foreground service so notification will be shown, in this notification you provide STOP button, so the user can stop music from there.
But if you want that your app's background service is stopped after removing from recent task then,
public class CustomService extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
//stop service
stopService(new Intent(this, CustomService.class));
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("CustomService", "Service Destroyed");
}
}
Now declare service in AndroidMenifest.xml
<service android:name=".CustomService" android:stopWithTask="false" />
android:stopWithTask="false" will give callback on onTaskRemoved(), so handle stop service over there.
leave the service running when the app is cleared from recent ,user can stop completely the audio and the service in the notification with a button just like this :
Here is a picture -> QQ Music
public class OnClearFromRecentService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("ClearFromRecentService", "Service Started");
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("ClearFromRecentService", "Service Destroyed");
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Log.e("ClearFromRecentService", "END");
//Code here
stopSelf();
}
}
Register this service in Manifest.xml like this
<service android:name="com.example.OnClearFromRecentService" android:stopWithTask="false" />
Then start this service on your activity
startService(new Intent(getBaseContext(), OnClearFromRecentService.class));
And now whenever you will clear your app from android recent Then this method onTaskRemoved() will execute.

android running background service even after killing the application

What I need?
I need something as startForeground() but I dont want to show any icon
What apps similars is?
Whatsapp, facebook etc
you can close their apps but a "service" continue running listening for notifications.
Well in my case I need a service for "Send data" event when app has crashed or has been closed.
#Override onStartCommand:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
to kill it use stopSelf(); , the rest of the service logic is up to you :)
You can do it by launching your service in a different process. In your AndroidManifest.xml add this to your service tag:
android:process="myNewProcess"

Android service: Start if Smartphone is rebooted and run if App is swiped away

I have an app with a service. This service should be started if the smartphone is rebooted. Anyway if the app was started during the switch off or not. And the app should be restarted (or still running) if the app is swiped away (killed). This work on my Smartphone with Android 4.2, but doesn't work on a Smartphone with Android 5.1.
I start my service in a class, derived from BroadcastReceiver:
#Override
public void onReceive(Context oContext, Intent oIntent)
{
if (oIntent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {
Intent oNewIntent = new Intent(oContext, CarFinderService.class);
// class can be anything which you want to start on bootup...
oNewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
oContext.startService(oNewIntent);
}
}
This works on Android 4.2., but not on Android 5.1. I thins this code is OK. Or not?
What can I do that a service is started on reboot or if the app is swiped away?
I tried different things, found via searching the web. But I found a solution who works on Android 5.1.
Any hints?
Thanks
Hans
Add this to you manifest for 5.1 :
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
To bring service back to live put this inside your service :
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleCommand(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
The money is in the START_STICKY.

How to make an android app to always run in background?

I'm using an android device. When I open the Settings > Apps > Running, there is an option on the top-left of the screen to see : (1) Running processes (2) Cached background processes. And the app(s) which I wanted to run always (24×7) is/are unfortunately listed under (2) Cached background processes, which I wanted it/them to be listed under (1) Running processes (if it is possible). Can it be done? Or in short, how to make an android app always run in the background?
I hope I conveyed the question :-)
You have to start a service in your Application class to run it always.
If you do that, your service will be always running. Even though user terminates your app from task manager or force stop your app, it will start running again.
Create a service:
public class YourService extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// do your jobs here
return super.onStartCommand(intent, flags, startId);
}
}
Create an Application class and start your service:
public class App extends Application {
#Override
public void onCreate() {
super.onCreate();
startService(new Intent(this, YourService.class));
}
}
Add "name" attribute into the "application" tag of your AndroidManifest.xml
android:name=".App"
Also, don't forget to add your service in the "application" tag of your AndroidManifest.xml
<service android:name=".YourService"/>
And also this permission request in the "manifest" tag (if API level 28 or higher):
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
UPDATE
After Android Oreo, Google introduced some background limitations. Therefore, this solution above won't work probably. When a user kills your app from task manager, Android System will kill your service as well. If you want to run a service which is always alive in the background. You have to run a foreground service with showing an ongoing notification. So, edit your service like below.
public class YourService extends Service {
private static final int NOTIF_ID = 1;
private static final String NOTIF_CHANNEL_ID = "Channel_Id";
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
// do your jobs here
startForeground();
return super.onStartCommand(intent, flags, startId);
}
private void startForeground() {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
startForeground(NOTIF_ID, new NotificationCompat.Builder(this,
NOTIF_CHANNEL_ID) // don't forget create a notification channel first
.setOngoing(true)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(getString(R.string.app_name))
.setContentText("Service is running background")
.setContentIntent(pendingIntent)
.build());
}
}
EDIT: RESTRICTED OEMS
Unfortunately, some OEMs (Xiaomi, OnePlus, Samsung, Huawei etc.) restrict background operations due to provide longer battery life. There is no proper solution for these OEMs. Users need to allow some special permissions that are specific for OEMs or they need to add your app into whitelisted app list by device settings. You can find more detail information from https://dontkillmyapp.com/.
If background operations are an obligation for you, you need to explain it to your users why your feature is not working and how they can enable your feature by allowing those permissions. I suggest you to use AutoStarter library (https://github.com/judemanutd/AutoStarter) in order to redirect your users regarding permissions page easily from your app.
By the way, if you need to run some periodic work instead of having continuous background job. You better take a look WorkManager (https://developer.android.com/topic/libraries/architecture/workmanager)
On some mobiles like mine (MIUI Redmi 3) you can just add specific Application on list where application doesnt stop when you terminate applactions in Task Manager (It will stop but it will start again)
Just go to Settings>PermissionsAutostart
In mi and vivo - Using the above solution is not enough. You must also tell the user to add permission manually.
You can help them by opening the right location inside phone settings. Varies for different phone models.

START_STICKY not working

I've asked a question about keeping service alive but I didn't find the solution so I have another simpler question.
android doc says if android kills a service with START_STICKY on return of onStartCommand in low memory state, it will recreate the service if I'm correct.
but this service gets killed and disappear in running tasks after a period of time but it didn't get recreated! I run this service in android 4.4.2 on my phone, when screen is on, it survived about 20 minutes
but when screen is off it disappeared after about 3 or 4 minutes... on my tablet (again android 4.4.2) it stayed longer, about 4 or 5 hours and then got disappeared again (I got different results on different tests). I even test it on android 5 and the result was similar to tablet with android 4.4.2
am I missing something here? I thought service wont get destroyed when we are using return START_STICKY until I call stopService
here's my service:
public class MyService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void onDestroy() {
super.onDestroy();
}
}
sry for bad english :)
May be useful for someone--
This problem has nothing to do with devices with AOSP based ROMs.So android 4.4.2 version is not an issue.
So there are some devices (HUAWEI,LAVA,XIAOMI) are shipped with pre-installed start managers or energy savers, and they run on customized android ROMs. so these devices generally dont entertain a sticky service.
So possible option is to implement something like watchdog timer and check the service in between, if not started, the service can be run again. Possible implications may be on battery consumption though.
The service does get re-created, not re-started.
If you override the onCreate and do a Log.d or a Toast, you will see that onCreate gets called after your activity and app is destroyed.
So the trick to keep it running after it is re-created is to do your code on the onCreate method and use the onStartCommand just to return START_STICKY.

Categories

Resources