Persistent Service on Android -
i trying write service comes mediaplayer. have different activities accessing it, thought best peruse service.
it works fine far, have added call startforeground, described here. notification shows up.
but when press home or button on device, service stopped , ondestroy called, , notification icon disappears. when return, service seems rebind fine.
i stop music playback on ondestroy, of course stops. keep notification , service alive when user on app.
edit: hope relevant part:
public class mediaplayerservice extends service { private static class playermessagehandler extends handler { private final mediaplayerservice owner; public playermessagehandler(mediaplayerservice owner) { this.owner = owner; } @override public void handlemessage(message msg) { // handle } } private static final int notification_id = 13138; private final messenger messenger = new messenger(new playermessagehandler( this)); private mediaplayer player; private notification notification; @override public ibinder onbind(intent intent) { startnotification(); return messenger.getbinder(); } @override public void oncreate() { super.oncreate(); log.v(tag, "media player service created."); player = new audiobookplayer(this); new thread(seekerupdate).start(); isrunning = true; } @override public int onstartcommand(intent intent, int flags, int startid) { log.v(tag, "received start id " + startid + ": " + intent); return start_sticky; } @override public void ondestroy() { super.ondestroy(); log.v(tag, "media player service destroyed."); if (player.isplaying()) { player.pause(); } sendmessagetoui(msg_player_has_paused); isrunning = false; } private void sendmessagetoui(int msg) { log.v(tag, "sending " + msg); sendmessage(message.obtain(null, msg)); } private void sendmessage(final message message) { // send } private void startnotification() { notificationcompat.builder builder = new notificationcompat.builder( this); builder.setsmallicon(r.drawable.notification); builder.setcontenttitle(getstring(r.string.app_name)); notification = builder.build(); startforeground(notification_id, notification); } } edit2: methods activity, taken here
@override protected void onstart() { super.onstart(); // bind service bindservice(new intent(this, mediaplayerservice.class), playerserviceconnection, context.bind_auto_create); } @override protected void onstop() { super.onstop(); // unbind service if (bound) { unbindservice(playerserviceconnection); bound = false; } }
you should make service sticky. in fact, tutorial uses:
public class helloservice extends service { ... @override public int onstartcommand(intent intent, int flags, int startid) { ... // if killed, after returning here, restart return start_sticky; } ... } edit: discussion transpired since, turns out suspicion correct, , hugo provided spot-on diagnosis. guess need add builder.setongoing(true); in startnotification().
Comments
Post a Comment