android - Converting Alarm Activity App into Service -


i have 1 app uses alarmmanager play specific song after every hour. problem is, app doesn't run in background long. observe gets killed after hour or so. result app doesn't play song whole day. want app run times , trigger alarmmanager play song. can how can convert app service run times, days?

below code snippets have.

mainacitivity.java-- main activity. purpose show ui users can choose hours when want song played:

@override protected void oncreate(bundle savedinstancestate) { .... .... intent intent=new intent(this,alarmreceiver.class); intent.setaction("hey ! first alarm event !"); mainactivityglobalinstance=this; mp=mediaplayer.create(this, r.raw.shanti); final int polling_seconds=1; final calendar cal=calendar.getinstance(); final pendingintent pi=pendingintent.getbroadcast(this, 0, intent, 0); final alarmmanager = (alarmmanager) getsystemservice(alarm_service); final button start=(button)findviewbyid(r.id.startalarm); final button stop=(button)findviewbyid(r.id.stopalarm); am.setrepeating(alarmmanager.rtc_wakeup, cal.gettimeinmillis(), polling_seconds*1000, pi); start.setenabled(false); stop.setenabled(true); stop.setonclicklistener(new button.onclicklistener() { public void onclick(view v){ am.cancel(pi); stop.setenabled(false); start.setenabled(true); } }); start.setonclicklistener(new button.onclicklistener() { public void onclick(view v){ am.setrepeating(alarmmanager.rtc_wakeup, cal.gettimeinmillis(), polling_seconds*1000, pi); stop.setenabled(true); start.setenabled(false); } }); }  public boolean onoptionsitemselected(menuitem item) { if(item.getitemid()==r.id.action_settings){ setflags(); intent intent=new intent(this,choosehours.class); startactivity(intent); return true; } return super.onoptionsitemselected(item); } 

in above main activity have instance created mediaplayer , alarmmanager

alarmreceiver.java-- extends broadcastreceiver , onreceive plays song if mediaplayer not running:

public class alarmreceiver extends broadcastreceiver {  @override public void onreceive(context ctxt, intent intent) { try{ if(intent != null && mainactivity.mp != null && mainactivity.mainactivityglobalinstance != null){ if(intent.getaction().equals("hey ! first alarm event !")){ calendar cal=calendar.getinstance(); if(cal.get(calendar.minute) == 0){ if( //conditions here ){ if(!mainactivity.mp.isplaying()) mainactivity.mp.start(); } } } } }catch(exception e){ toast.maketext(ctxt, "error occured: "+e.tostring(), toast.length_long).show(); }  }  } 

choosehours.java -- activity presents ui choose hours

appreciate help.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -