How to run background service for Instant Messagin

2019-08-20 17:20发布

问题:

Android Oreo has released with many restrictions on running background services/Task. Services now don't behave like normal in Oreo as they used to before.

But what if I have to run a service in background for 24*7 for Instant Messaging.

I am developing an application for Instant messaging using kurento Third Party API. To achieve this I will have to run a background service which communicate with server for new messages.

Lower then Oreo its working fine.

How do I prevent android system to not kill the service?.

I don't want to show a notification all time while my service is running because i will run my service for 24*7 for new messages so it feels cheap UI Experience to user.

回答1:

After Nougat version the way back ground service is changed. If you want your background service to work, you can do as mentioned in the code below. In IntentService, the life cycle method onCreate() is called. And in this method add below code.

  @Override
public void onCreate() {
    super.onCreate();

    int NOTIFICATION_ID = (int) (System.currentTimeMillis()%10000);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForeground(NOTIFICATION_ID, new Notification.Builder(this).build());
    }

}

And when you are calling service, call your service via blow code

  Intent intent = new Intent(context, FindNumberService.class);
    intent.putExtras(bundle);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context.startForegroundService(intent);
    }
    else {
        context.startService(intent);
    }

Hope this will help you.



回答2:

As the way to do, you should modify logic of incoming signals to use as channel for incoming messages push notifications. When app goes to background, you have to rely on push notifications with high priority.

And after got push, you can carry out all needed stuff.