update Ui from TimerTask in android
In my application i have to send lati and lang values to server every 5 min.
Through timer task and (using service(my requirement is service thats why i am using service you can use activity itself)) i achieved this one.
Sample code
public class VehicleTrackingService extends Service {
private Timer timer = new Timer();
private static final long UPDATE_INTERVAL = 300000;
Location l = null;
LocationManager lm;
String userid;
public void onCreate() {
super.onCreate();
SharedPreferences sharedPreferences = getSharedPreferences(
DizlaActivity.PREFS_NAME, MODE_PRIVATE);
userid = sharedPreferences.getString("user_id", "");
locationUpdates();
}
private void locationUpdates() {
@Override
public void onDestroy() {
super.onDestroy();
if (timer != null) {
}
In my application i have to send lati and lang values to server every 5 min.
Through timer task and (using service(my requirement is service thats why i am using service you can use activity itself)) i achieved this one.
public class VehicleTrackingService extends Service {
private Timer timer = new Timer();
private static final long UPDATE_INTERVAL = 300000;
Location l = null;
LocationManager lm;
String userid;
public void onCreate() {
super.onCreate();
SharedPreferences sharedPreferences = getSharedPreferences(
DizlaActivity.PREFS_NAME, MODE_PRIVATE);
userid = sharedPreferences.getString("user_id", "");
locationUpdates();
}
private void locationUpdates() {
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
int i = 0;
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);
for (int j = providers.size() - 1; j >= 0; j--)
{
l = lm.getLastKnownLocation(providers.get(i));
if (l != null)
break;
}
if (l==null) {
return;
}
final String lat = String.valueOf(l.getLatitude());
final String log = String.valueOf(l.getLongitude());
// do some values send to server method here
}
}, 0, UPDATE_INTERVAL);
}
@Override
public void onDestroy() {
super.onDestroy();
if (timer != null) {
timer.cancel();
}
}}
This is one of the glamorous and Important post.I like your blog Philosophy.This is one of the genius post.
ReplyDeletethank you
Delete