2011-07-05 90 views
0

這裏是代碼。Android手機啓動後獲取GPS位置,我試圖在服務中獲取它,但位置返回爲零

我怎樣才能確定,該位置返回alwasys而不是null。

package com.test.location; 
import android.app.Service; 
import android.content.Context; 
import android.content.Intent; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.os.Looper; 
import android.util.Log; 
public class NotifyOnBoot extends Service { 
     Location location; 

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

     @Override 
     public void onCreate() { 
        super.onCreate(); 

        updateNotification(); 

        Thread th = new Thread(null, task, "myService"); 
        th.start(); 
     } 

     private Runnable task = new Runnable() { 
     public void run() { 

      if(location == null) 
      { 
       Log.d("location","No location"); 
      } 
      else 
       Log.d("location",location.toString()); 


      NotifyOnBoot.this.stopSelf(); 
     } 
    }; 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
    } 

    @Override 
    public int onStartCommand (Intent intent, int flags, int startId){ 
      return START_STICKY; 
    } 


    protected void updateNotification() 
    { 
     LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
     LocationListener locationListener = new MyLocationlistener(); 
     lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); 
     location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
    } 
    private class MyLocationlistener implements LocationListener{ 
     public void onLocationChanged(Location location){} 
     public void onProviderDisabled(String provider){} 
     public void onProviderEnabled(String provider){} 
     public void onStatusChanged(String provider, int status, Bundle extras){} 
    } 
} 

回答

0

我建議創建一個回調接口,並使用onLocationChanged該通知回調的時刻的位置發起的第一次。

LocationProvider locationProvider = LocationManager.NETWORK_PROVIDER; 
// Or use LocationManager.GPS_PROVIDER 

Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider); 

我希望這對你有所幫助。

+0

你可以請具體:) –

+0

創建一個處理程序並將其用作回調。所以當處理程序被調用時,只需使用lat長座標。 –

+0

hmm,任何示例代碼都會很好 –