I have a task to periodically read the phone sensors (e.g. WiFi, accelerometer) in the backend.
My current solution is to use an AlarmManager.
Specifically, we have:
In the "main" program (an activity), we use PendingIntent.getService:
public class Main extends Activity { ... Intent intent = new Intent(this, AutoLogging.class); mAlarmSender = PendingIntent.getService(this, 0, intent, 0); am = (AlarmManager)getSystemService(ALARM_SERVICE); am.setRepeating(AlarmManager.RTC, 0, 5*1000, mAlarmSender); }
In the "AutoLogging" program (a service), we respond to the alarm periodically:
public class AutoLogging extends Service { ... @Override public void onCreate() { Toast.makeText(this, "onCreate", Toast.LENGTH_SHORT).show(); } @Override public void onDestroy() { super.onDestroy(); Toast.makeText(this, "onDestroy", Toast.LENGTH_SHORT).show(); } @Override public boolean onUnbind(Intent intent) { Toast.makeText(this, "onUnbind", Toast.LENGTH_SHORT).show() return super.onUnbind(intent); } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); Toast.makeText(this, "onStart", Toast.LENGTH_SHORT).show(); // Read sensor data here } @Override public IBinder onBind(Intent intent) { Toast.makeText(this, "onBind", Toast.LENGTH_SHORT).show(); return null; } }
My problem is:
When I use this alarm service, only OnCreate and OnStart are called at each alarm.
My questions are:
(1) Do we need to call OnDestroy (or onBind, onUnbind)?
(2) Is this a correct way to use AlarmManager (compared with "broadcase receiver")?
Thanks! Vincent