Background Service for Android Oreo

Background service for android oreo

If you would have read the Android Oreo 8.0 Documentation properly somewhere in here, you might not have posted this question here.

Step 1: Make sure you start a service as a foreground Service as given in below code

ContextCompat.startForegroundService(mainActivity, new Intent(getContext(), GpsServices.class));
ContextCompat.startForegroundService(mainActivity, new Intent(getContext(), BluetoothService.class));
ContextCompat.startForegroundService(mainActivity, new Intent(getContext(), BackgroundApiService.class));

Step 2: Use notification to show that your service is running. Add below line of code in onCreate method of Service.

@Override
public void onCreate() {
...
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForeground(NOTIFICATION_ID, notification);
}
...
}

Step 3: Remove the notification when the service is stopped or destroyed.

@Override
public void onDestroy() {
...
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
stopForeground(true); //true will remove notification
}
...
}

One problem with this solution is that it will keep showing the notification until your Service is running on all devices running on Android Oreo 8.0.

I'm sure that this solution will work even when the app is in the background or in kill state.

IMPORTANT NOTE: SHOWING A NOTIFICATION FOR RUNNING A SERVICE IN BACKGROUND (APP IN BACKGROUND OR KILLED STATE) IS MANDATORY IN ANDROID OREO 8.0. YOU CANNOT RUN AWAY WITH IT. SO IT IS RECOMMENDED THAT YOU MAKE NECESSARY CHANGES IN YOUR APP TO MAKE IT WORK PROPERLY AS PER THE BEST PRACTICES FOLLOWED OR ASKED BY ANDROID.

I hope this might help to solve your problem.

Background services Android oreo (limitation)

App in Foreground - Best option is to use service or Intent Service if you need to some task when application is open or in the stack.

App in Background - If you want to perform some long running periodic operation then best option is to use Jobservice running in background and Jobscheduler implementation to schedule that jobservice. Android O and above JobScheduler is recommended for background operations.

Oreo Background Services

But we saw that when the application is killed, the Foreground Service dies also after a few minutes. Should it happen? Should the Foreground Service will only continue to work if the app is in the background?

Yes it destroys foreground service.., But it recreates again within the microseconds... Its natural behaviour. Even if you killed app by swiping it away from recent apps..!!

Post your foreground service code only..!! with no extra code and i will correct it so that it can behave the way i stated..

Also, if this is the case what does the Battery Optimization feature do? Keeps the Service working while in background only? Can the Service still be killed while the app is the background with this feature on?

If battery is optimising then it might not re launch your foreground service too ON_BOOT_COMPLETE

I've read a lot of docs regarding it but I'm still confused regarding the state of Service when the application is killed.

Yes, i know it is total waste of time as google documentation is having no straight forward ways in documenting and there are no sample codes for developers... If you wants to code for more than 4 android os then all codes needed to coded as per version codes..!!

We do not mind showing a notification for those services but we still want it to continue to work "endlessly".

It never happens... ENDLESSLY must be implemented with the broadcastreceivers as and and when you wants your services can seem to be running endlessly.. Again you can not create static receivers and can not call them via manifest as before... You need to create it from a foreground service in runtime.

Where i can get example codes?
No where... Google has no sample codes... just blah blah blah...

Short and sweet... I had lost my complete year and now well known about all above your questions and have implemented it in apps and apps are in market running quite good as expected... And i like to help them all as google lacks it in documentation.. Post your code , Let me know, and Get it worked from me


Edit : 2

Google has made wrong os ( Android ) based on wrong concept with wrong implementation with wrong support with wrong documentation with wrong License which is open source which allows non - standard companies to modify and use it.. Now Consider its dis-advantages :

  1. It frustrates developers to code an app which even supports for more than one version.. Say Lollipop and Marshmallow. Both ways are different and already developer has 1000 cases to handle and then again this..
  2. Case becomes worst to develop when it comes to develop more than 2 versions at a time... Its a complete mess..
  3. Again google keep changing rules over few months of time...
  4. With no proper documentation makes developers only one option open is to pull the hairs out..!!
  5. These all was not sufficient ..., so again :-

Vivo : ColorOs
OnePlus : OxygenOs
MI : FunTouchOs
.
.
.
.

This is huge list of companies who does not know how to modify ( and why to modify...? ) started modifying stock-android.., most of which only allows facebook, Google, Whatsapp, Instagram, major social app vendors services only to come in memory on Boot_complete.

Why only these services and why not mine..?

Because buyers wont buy a phone on which above softwares will not work..!! No one will take such phones..!!

Why not mine..?

This is a business

Is there any other way...?

No way..!! As we develop apps standardly on Googles Android Studio and also tests it on emulators of google which holds stock-android systems..!! So don't guranty will it work on every manufacturers device or not..!!

Who is responsible for these all situations.. and what is solution..?

Google is responsible for these all frustrations and all the mobile phone manufactures has taken it the such extent which is now impossible to handle.. Google has to come with restriction on modifications and also hardware support systems must be implemented..!! Best way to dis-continue such unmanaged operating system.

Start App From Service in BackGround in oreo and newer

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 :

  1. set a alarm from Activity with Calendar & PendingIntent in AlarmManger to run my Service in a specific time

  2. 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).

  3. 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);

Background service issue in oreo and pie

Yes you need to add notification on start you service

public class LocationService extends Service implements CallbackResponseListener, LocationListener {

public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.e("Service Started", "onStartCommand!");
createNotificationChannel();
startTimer();
return START_STICKY;
}
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Service channel";
String description = "Service channel description";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("12", name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);

PendingIntent intent = PendingIntent.getActivity(getApplicationContext(), 0,
notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, "12")
.setContentTitle("Title")
.setContentText("App is running in background for location")
.setSmallIcon(R.drawable.notification_icon).setContentIntent(intent)
.build();
startForeground(2001, notification);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e("Service EXIT", "ondestroy!");
Intent broadcastIntent = new Intent(getApplicationContext(), LocationBroadcastReceiver.class);
sendBroadcast(broadcastIntent);

stoptimertask();
}

@Override
public IBinder onBind(Intent intent) {
return null;
}
public void startTimer() {
//set a new Timer
try {
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, to wake up every 1 second
timer.schedule(timerTask, AppConstants.bgTaskStartDelay,2000); //
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* it sets the timer to print the counter every x seconds
*/
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
try {
// add your code here for schedule

} catch (Exception e) {
e.printStackTrace();
}
}
};
}
}


Related Topics



Leave a reply



Submit