user340
user340

Reputation: 383

Using wakelock Android

I am checking the location data once every 5 mins. I have this implemented in a service which gets called every five mins. On the main activity I have two buttons to start/ stop the alarm. Is this the best place to implement the lock..

 startService.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            // add a notification when the BG service is started..

            Intent myIntent = new Intent(ContextActivity.this, MyAlarmService.class);
            pendingIntent = PendingIntent.getService(ContextActivity.this, 0, myIntent, 0);

                        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

                        Calendar calendar = Calendar.getInstance();
                        calendar.setTimeInMillis(System.currentTimeMillis());
                        calendar.add(Calendar.SECOND, 10);
                       // alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
                        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 5, pendingIntent);

               Toast.makeText(ContextActivity.this, "Start Alarm", Toast.LENGTH_LONG).show();
               System.out.println("Alarm started");
        }

    });

    stopService.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
               alarmManager.cancel(pendingIntent);

                        // Tell the user about what we did.
                        Toast.makeText(ContextActivity.this, "Cancel!", Toast.LENGTH_LONG).show();
                        System.out.println("Stop alarm");
        }
    });

Is it ok to acquire the lock in the start and release the lock in stop?

Upvotes: 0

Views: 593

Answers (1)

FoamyGuy
FoamyGuy

Reputation: 46846

You shouldn't need a wakelock for this.

You are already using alarmManager.setRepeating(AlarmManager.RTC_WAKEUP... which as the docs state:

Alarm time in System.currentTimeMillis() (wall clock time in UTC), which will wake up the device when it goes off.

So your alarm will already wake up the device for you when it fires. If you feel that your service will not be done with its work before the devices falls back asleep then you should be acquiring the wake lock inside of the service and releasing it after you are done with your work.

Upvotes: 2

Related Questions