开发者

Android: Service stops when Activity is closed

开发者 https://www.devze.com 2023-01-26 16:15 出处:网络
If I understand it correctly, bindService() with BIND_AUTO_CREATE will start a service and will not die until all bindings are all unbinded.

If I understand it correctly, bindService() with BIND_AUTO_CREATE will start a service and will not die until all bindings are all unbinded.

But if I bindService(BIND_AUTO_CREATE) at onCreate() and hit back button to close the activity, the service calls onDestroy() and dies also.

I don't call unbind() at anytime. So is that mean when the Activity got destroyed, the binding got destroyed also and the service gets destroyed also?

What if I want the service to be always running, at the same time when the activity starts I want to bind it so that I can access the service?

If I call StartService() and then bindService() at onCreate(), it will restart the service at every launch of Activity. (Which I don't want).

So I could I start service开发者_C百科 once and then bind next time I launch the activity?


You need to use startService so that the service is not stopped when the activity that binds to it is destroyed.

startService will make sure that the service is running even if your activity is destroyed (unless it is stopped because of memory constraints). When you call startService, the onStart method is called on the service. It doesn't restart (terminate and start again) the service. So it depends on how you implement the onStart method on the Service. The Service's onCreate, however, is only called once, so you may want to initialize things there.


I found a solution!

The problem is when you close your activity and your service is not configured as a foreground service, android system will recognize it as unused and close it.

here's an example where I added a notification :

void setUpAsForeground(String text) {
    PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0,
            new Intent(getApplicationContext(), MainActivity.class),
            PendingIntent.FLAG_UPDATE_CURRENT);
    mNotification = new Notification();
    mNotification.tickerText = text;
    mNotification.icon = R.drawable.muplayer;
    mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
    mNotification.setLatestEventInfo(getApplicationContext(), "MusicPlayer",
            text, pi);
    startForeground(NOTIFICATION_ID, mNotification);

}

(A foreground service is a service that's doing something the user is actively aware of (such as playing music), and must appear to the user as a notification. That's why we create the notification here)


you can do it with BroadcastReceivers. you'll find a lot on google how to use them

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号