android - Starting up Service with AlarmManager , which already might be running -
i need run service in time interval, example every 2 minutes. register alarmmanager, works fine when service stops before 2 minutes up, there great chance take more 2 minutes, in case i'll need service terminated , start new one, how can this?
alarmmanager = (alarmmanager) getsystemservice(context.alarm_service); intent = new intent(getapplicationcontext(), sender.class); pendingintent pi = pendingintent.getservice(getapplicationcontext(), 0, i, 0); am.setrepeating(alarmmanager.rtc_wakeup,system.currenttimemillis(),1000 * 30, pi);
instead of starting service alarmmanager
use broadcast. set alarmmanager
send broadcast intent. create own broadcastreceiver
receive intent , in onreceive
method restart(stop , start) service.
//start alarmmanager sending broadcast intent intent = new intent(context, mybroadcastreceiver.class); // explicit peningintent = pendingintent.getbroadcast(context, 0, intent, 0); malarmmanager.setrepeating(alarmmanager.rtc_wakeup, system.currenttimemillis(), 30 * 1000, pendingintent);
.
//broadcastreceiver public class mybroadcastreceiver extends broadcastreceiver { @override public void onreceive(context context, intent intent) { intent serviceintent = new intent(synchronizationservice.class.getname()); context.stopservice(serviceintent); context.startservice(serviceintent); } }
.
//register receiver in androidmanifest.xml in application tag <receiver android:name="com.example.mybroadcastreceiver" > </receiver>
Comments
Post a Comment