Reputation: 3212
I want to fetch user location every 5 minutes and display as Toast
. Which is the best way to do this? Service
or IntentService
? I want to start and stop the service on button click. How to do that?
Upvotes: 2
Views: 4977
Reputation: 1843
Use sticky Service to do this
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(LOG_TAG, "Service Started");
try {
}
} catch (Exception e) {
e.printStackTrace();
}
return START_STICKY;
}
Then call this from oncreate of service
protected void onHandleIntent(Intent intent) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Log.e(LOG_TAG, "Awake - "+i);
// Log.i(LOG_TAG,"TEST ALARM TIME");
// do your task -- here get location
//change the time interval as per your need.
handler.postDelayed(this, 300000);
}
},1000);
}
Upvotes: 0
Reputation: 8210
You can do that with LocationManager, you need to set time interval.
example
LocationManager = new LocationManager();
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Parameters
provider String: the name of the provider with which to register
minTime long: minimum time interval between location updates, in milliseconds
minDistance float: minimum distance between location updates, in meters
listener LocationListener: a LocationListener whose
onLocationChanged(Location) method will be called for each location update
you can read more on this page LocationManager
Upvotes: 0
Reputation: 2106
Use a alarm service to trigger location service which will inturn save location in database table
public static void setAlarmTimely(Context context) {
AlarmManager alarmMgr;
PendingIntent alarmIntent;
alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra(IntentConstants.ALARM_INTENT, IntentConstants.INTENT_REQUEST_CODE_LOCATION_TRACK);
alarmIntent = PendingIntent
.getBroadcast(context, IntentConstants.INTENT_REQUEST_CODE_LOCATION_TRACK, intent, 0);
alarmMgr.cancel(alarmIntent);
Calendar calendar = Calendar.getInstance();
LOGD(TAG, time + " ");
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis() + locationCaptureTime * 60 * 1000,
5 * 60 * 1000, alarmIntent);
}
on button click cancel the alarm
AlarmManager alarmMgr;
PendingIntent alarmIntent;
LOGD(TAG, "cancelling location update");
alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra(IntentConstants.ALARM_INTENT, IntentConstants.INTENT_REQUEST_CODE_LOCATION_TRACK);
alarmIntent = PendingIntent
.getBroadcast(context, IntentConstants.INTENT_REQUEST_CODE_LOCATION_TRACK, intent, 0);
alarmMgr.cancel(alarmIntent);
Upvotes: 4