Android : Using GPS on Services

on Saturday, October 25, 2014


On this code i want to get the gps location every 3 seconds. but when i run this program on my device it tells me that latitude and longitude are both 0 every time. how should i handle this problem? and what is the looper task ?? it gives me error when i donot use it



public class LocationService extends Service {

final static String TAG = "MyService";
double latitude ;
double Longitude ;
LocationManager lm;
LocationListener ll;

@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onCreate() {

Log.d(TAG, "onCreate");
super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread() {
public void run() {
Looper.prepare();
while(true){
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
ll = new MyLocationListener();

lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 0, ll);
//when i log here , it gives me wronganswer
Log.d(TAG,Double.toString(latitude));
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.d(TAG, "OnDestroy");
super.onDestroy();
}

class MyLocationListener implements LocationListener{
@Override
public void onLocationChanged(Location location) {
//when i log here , it gives me correct answer
double lat = location.getLatitude();
double lon = location.getLongitude();
latitude = lat;
Longitude = lon;
}
@Override
public void onProviderDisabled(String arg0) {
}

@Override
public void onProviderEnabled(String arg0) {
}

@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
};
}

0 comments:

Post a Comment