2011-12-15 102 views
1

我正在編寫一個返回經度和緯度的Android應用程序,但是位置保留一個空值。位置返回NULL

請看看你是否能看到爲什麼,它一直在竊聽我。代碼如下:

public class example extends Activity { 

    public static double latitude; 
    public static double longitude; 
    LocationManager lm; 
    LocationListener ll; 
    Location location; 


    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.questions); 


     lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 

     ll = new MyLocationListener(); 

     lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll); 
     //location = lm.getLastKnownLocation(lm.getBestProvider(criteria, true)); 

     Button b = (Button) findViewById(R.id.button2); 
     b.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View arg0) { 
      String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); 
      int index1 = provider.indexOf("gps"); 
      if(index1 < 0) 
       // gps not enabled, call msgbox  
       showMsgBox("GPS is off", "GPS is off. Turn it on?", "Turn on"); 
      else 
      areWeThereYet(); }}); 
} 

    private void areWeThereYet() 
    { 
     if(weAreThere()) 
     { 
      toastMsg("in correct place");  
     } 
     else if(location!=null) 
      toastMsg("not there yet"); 
    } 

private boolean weAreThere() { 

    location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); 

    if (location!=null) 
    { 
     longitude = location.getLongitude(); 
     latitude = location.getLatitude(); 
     toastMsg(latitude + " " + longitude); 
     return inCorrectPlace(question); 
    } 
    else 
    { 
     toastMsg("Location not ready yet"); 
     return false; 
    } 
} 

private void toastMsg(String msg) { 
     Toast toast = Toast.makeText(this, msg, 2000); 
     toast.setGravity(Gravity.BOTTOM, 0, 0); 
      toast.show(); 
} 
} 

回答

3

如果自設備啓動以來GPS沒有得到位置,則位置對象將爲空。您可以做的一件事就是嘗試獲取GPS位置和網絡位置,並檢查兩個以查看它們中的任何一個是否良好(或哪個更好)並使用該位置。

2

如果您正在使用模擬器,請參閱here以獲取有關設置模擬器以提供位置的建議。如果您在設備上進行測試,可能是因爲您從未擁有過gps位置。在測試您的應用之前,請嘗試使用Google地圖應用。