android - background services stop when the app is closed via the BACK button -
a background service in android stops running when user exits app using button. same service works fine if app in foreground or in background (clicking home button).
there 3 cases:
- keep app running: every 15 seconds notification shown (ok).
- put app in background clicking home button: notifications keep showing (ok)
- click button (this closes app): background service stopped , no more notifications shown (bug)
expected behavior
also in case #3, notifications should keep running every 15 seconds.
my entire source below
mainactivity.java
package com.example.service_demo; import android.app.activity; import android.app.activitymanager; import android.app.activitymanager.runningserviceinfo; import android.content.broadcastreceiver; import android.content.context; import android.content.intent; import android.content.intentfilter; import android.os.bundle; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.textview; import android.widget.toast; public class mainactivity extends activity implements onclicklistener { private textview timervalue; private button starttimer; private button cancletimer; intent i; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); mapview(); } private void mapview() { timervalue = (textview) findviewbyid(r.id.timertext); starttimer = (button) findviewbyid(r.id.starttimer); cancletimer = (button) findviewbyid(r.id.cancletimer); starttimer.setonclicklistener(this); cancletimer.setonclicklistener(this); } @override protected void onresume() { super.onresume(); = new intent(this, simpleservice.class); if (ismyservicerunning()) { toast.maketext(getbasecontext(), "service running,", toast.length_short).show(); registerreceiver(broadcastreceiver, new intentfilter( simpleservice.broadcast_action)); starttimer.setenabled(false); } else { toast.maketext(getbasecontext(), "there no service running", toast.length_short).show(); } } @override public void onclick(view v) { if (v == starttimer) { starttimer.setenabled(false); = new intent(this, simpleservice.class); startservice(i); registerreceiver(broadcastreceiver, new intentfilter( simpleservice.broadcast_action)); } else if (v == cancletimer) { = new intent(this, simpleservice.class); stopservice(i); timervalue.settext("00:00:00"); starttimer.setenabled(true); } } private broadcastreceiver broadcastreceiver = new broadcastreceiver() { @override public void onreceive(context context, intent intent) { updateui(intent); } }; private void updateui(intent intent) { string str = intent.getstringextra("textval"); timervalue.settext(str); } private boolean ismyservicerunning() { activitymanager manager = (activitymanager) getsystemservice(context.activity_service); (runningserviceinfo service : manager .getrunningservices(integer.max_value)) { if (simpleservice.class.getname().equals( service.service.getclassname())) { return true; } } return false; } @override protected void onstop() { // todo auto-generated method stub super.onstop(); = new intent(this, simpleservice.class); startservice(i); } @override public void onbackpressed() { // todo auto-generated method stub super.onbackpressed(); system.exit(0); // system.exit(0) mendatory app can't // removed } }
simpleservice
package com.example.service_demo; import java.util.timer; import java.util.timertask; import android.os.binder; import android.os.bundle; import android.os.ibinder; import android.app.activity; import android.app.notification; import android.app.notificationmanager; import android.app.pendingintent; import android.app.service; import android.content.intent; import android.view.menu; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.toast; public class simpleservice extends service { private notificationmanager mnm; private long starttime = 0l; long timeinmilliseconds = 0l; long timeswapbuff = 0l; long updatedtime = 0l; long basestart = system.currenttimemillis(); timer timer = new timer(); long timeswap = 0l; int secs = 0; int mins = 0; int hour = 0; intent intent; string s; public static final string broadcast_action = "com.example.service_demo.mainactivity"; private int notification = 1; @override public ibinder onbind(intent intent) { return null; } @override public void oncreate() { super.oncreate(); mnm = (notificationmanager) getsystemservice(notification_service); intent = new intent(broadcast_action); toast.maketext(this, "service started", 2000).show(); } @override public int onstartcommand(intent intent, int flags, int startid) { thread t = new thread(new runnable() { @override public void run() { timer.schedule(new remindtask(), 0, 1000); } }); t.start(); return service.start_not_sticky; } @override public void ondestroy() { super.ondestroy(); mnm.cancel(notification); if (timer != null) { timer.cancel(); timer.purge(); timer = null; } toast.maketext(this, "service stoped", 2000).show(); } class remindtask extends timertask { @override public void run() { timeinmilliseconds = system.currenttimemillis() - basestart; timeswapbuff = timeswap; updatedtime = timeswapbuff + timeinmilliseconds; secs = (int) (updatedtime / 1000); mins = secs / 60; hour = mins / 60; secs = secs % 60; mins = mins % 60; s = "" + string.format("%02d", hour) + ":" + "" + string.format("%02d", mins) + ":" + string.format("%02d", secs); if (s.equalsignorecase("00:00:15")) { shownotification(); } intent.putextra("textval", s); sendbroadcast(intent); } } private void shownotification() { // in sample, we'll use same text ticker , // expanded notification charsequence text = s; // set icon, scrolling text , timestamp @suppresswarnings("deprecation") notification notification = new notification(r.drawable.ic_launcher, text, system.currenttimemillis()); // pendingintent launch our activity if user selects // notification pendingintent contentintent = pendingintent.getactivity(this, 0, new intent(this, mainactivity.class), 0); // set info views show in notification panel. notification.setlatesteventinfo(this, "notification label", text, contentintent); // send notification. mnm.notify(notification, notification); } }
in method onstartcommand()
of service, return start_sticky
. service continue run until explicitly call stopself()
in service or call stopservice()
activity.
thanks for providing me useful information about android background services.
ReplyDeleteLookup Past Employment Records in USA
Excellent blog, I really liked it, do share more updates. Check out at : nursing career information in new york
ReplyDeleteNice information shared, I appreciated your work Thank you. Visit here Nursing Career Information
ReplyDeleteThank you, Nice information shared, I appreciated your work Thank you.
ReplyDeleteVisit here:- OT staffing company in New York
I appreciated your work keep it up. Keep aware of people just by writing that kind of informative material. Thank you. Visit here:- Nursing Assistant Jobs in Pennsylvania
ReplyDeleteTry to post this kind of useful content blog posts. so that everyone aware of the situation. I appreciated your work Thank you.
ReplyDeleteVisit here:- Therapist recruiting company in New York
Thanks for sharing such an informative article, I appreciated your work keep it up.
ReplyDeleteVisit here nursing assistant jobs in Pennsylvania
I really liked it, do share more updates. Thank you. Check out at : RN jobs in Brooklyn
ReplyDeleteThanks for sharing this. Try to post this kind of useful content blog posts. so that everyone aware of the situation. I appreciated your work Thank you. Visit here:- PTA staffing company in New York
ReplyDeleteI appreciated your work Thank you, I really liked it, do share more updates.
ReplyDeleteCheck out at : RN jobs in Brooklyn