Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
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?

Java
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 wrong answer 							

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) {
			}
     };
}
Posted

1 solution

 
Share this answer
 
Comments
Kasra Ahmadi 25-Oct-14 12:36pm    
Thank you so much :D
Peter Leow 25-Oct-14 21:39pm    
You are welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900