Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

java - Background service for android oreo

How to continue background service in android Oreo without showing notification dot? i continues my background service using notification but i don't want to show notification for running service.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...