0

i have made a service in my project and i want to start the start after every 2mins. i am using the folowing code but its not working properly.

public class ScheduleSync extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) 
    {
        AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        Intent i = new Intent(context, StartMyServiceReceiver.class);
        PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,PendingIntent.FLAG_CANCEL_CURRENT);
        Calendar cal = Calendar.getInstance();
        service.setInexactRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(), 60000*2, pending);

    }

}



public class StartMyServiceReceiver extends BroadcastReceiver
{    
    public void onReceive(Context context, Intent intent) 
    {
        Toast.makeText(context, "receive broadcast", Toast.LENGTH_LONG).show();
        Log.d("StartMyServiceReceiver", "receive broadcast");
        Intent service = new Intent(context, myservice.class);
        context.startService(service);
    }
}

kindly help me regarding this issue. when i see the taskmanager myservice is running at backend.

user2064024
  • 531
  • 2
  • 7
  • 20

1 Answers1

0

Why using AlarmManager?

Just use Thread.sleep(xxxx):

public class ScheduleSync extends BroadcastReceiver{
    private Context context;
    private void startOtherService(){
        Intent i = new Intent(context, StartMyServiceReceiver.class);
        context.startService(i);
    }
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        this.context = context;
        new Thread(new Runnable(){
            public void run(){
                try{
                    Thread.sleep(2*60*1000);
                    startOtherService();
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

}
Jayyrus
  • 12,961
  • 41
  • 132
  • 214
  • not working in my case ... when i see in taskmanager service is running. in servce i m sending a notification in status bar. according to de code above it should send the notification after every 2mins but its not doing so. – user2064024 Mar 28 '13 at 07:12
  • try to change the second service to service instead broadcastreceiver. The second one must not be a broadcastreceiver because you know when the notification is arrived so you just send it to another SERVICE – Jayyrus Mar 28 '13 at 07:15
  • i think this is not work in Broadcast reciver. because When handling a broadcast, the application is given a fixed set of time (currently 10 seconds) in which to do its work. If it doesn't complete in that time, the application is considered to be misbehaving, and its process immediately tossed into the background state to be killed for memory if needed. check this for more detail http://stackoverflow.com/a/7460334/1168654 – Dhaval Parmar Mar 28 '13 at 07:26