vikramagain
vikramagain

Reputation: 123

Android: Scheduling application to start with repeating alarms not working

I get my Broadcast receiver to set a recurring alarm, to fire up a service. Unfortunately this does not result in the service being called repeatedly (based on logcat). I've experimented with different values for the time interval too. Can someone help? (I'm testing through Eclipse on Android 3.2 Motorola xoom)

Below is the code for the Broadcast receiver.

    alarm = (AlarmManager) arg0.getSystemService(Context.ALARM_SERVICE);
    Intent intentUploadService = new Intent (arg0, com.vikramdhunta.UploaderService.class);

    Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 3);

    PendingIntent pi = PendingIntent.getBroadcast(arg0, 0, intentUploadService , 0);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 5, pi);

Below is the code for the Service class

    public UploaderService()
    {
        super("UploaderService");
        mycounterid = globalcounter++;
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        synchronized(this)
        {
            try
            {
                for (int i = 1;i < 5;i++)
                {
// doesn't do much right now.. but this should appear in logcat
                    Log.i(TAG,"OK " + globalcounter++ + " uploading..." + System.currentTimeMillis());

                }
            }
            catch(Exception e)
            {

            }
        }   
    }
     @Override
        public void onCreate() {
            super.onCreate();
            Log.d("TAG", "Service created.");
        }


        @Override
        public IBinder onBind(Intent arg0) {
            return null;
        }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) 
    {
        Log.i(TAG, "Starting upload service..." + mycounterid);
        return super.onStartCommand(intent,flags,startId);
    }

Upvotes: 1

Views: 363

Answers (1)

vikramagain
vikramagain

Reputation: 123

Ok Looks like I got this one. Two changes were needed -
1 - i made a mistake of using PendingIntent.getBroadcast when I needed to do getService instead (hell, who knew!)
2 - In getService, I should have supplied PendingIntent.FLAG_UPDATE_CURRENT in the end instead of 0. FLAG_ONE_SHOT did not work. I guess since the interval is only 5 seconds, this is the right way.

Now I get the right service/function to be called every 5 seconds. Hurray!

Upvotes: 2

Related Questions