2016-07-23 55 views
1

我試圖獲取該位置的值。 我調試的代碼,我看到後,我得到的位置 - Android工作室不返回到主要活動的價值我得到的GPS /網絡位置android刪除位置的值

我看到有沒有例外的代碼。

方法'getCurrentLocation'返回位置。 後,我從GPS /網絡得到的位置(右位置accourding到調試觀衆)我看到的代碼只是爲了行

'if (!isGpsEnable && !isNetworkEnable) {' 

,並在「位置」返回空 變量甚至認爲'location'變量包含正確的gps位置。

代碼:

public class TraceLocation implements LocationListener 
{ 
public Location getCurrentLocation(Context context) 
{ 
    Location location = null; 

    try { 

     LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); 

     Boolean isGpsEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
     Boolean isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

     if (!isGpsEnable && !isNetworkEnable) { 
      // TODO !!! => no gps and no network !!! 
     } else if (context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 
      if (isNetworkEnable) { 
       locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 10, this); 

       if (locationManager != null) { 
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
       } 
      } 

      if (isGpsEnable) { 
       locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 10, this); 

       if (locationManager != null) { 
        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
       } 
      } 
     } 
    } 
    catch(Exception e) 
    { 

    } 


    return location; 
} 

問題:

  • 使用我的Android 6.0(棉花糖)

    1. 爲什麼我得到空的結果時,該方法即使當我看到調試的返回值不爲null時也會返回

    2. 當我刪除

      locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,60000,10,這一點);

 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 10, this); 

我不上的調試也得和地點 - 爲什麼?????

+0

你的問題到底是什麼? :) 你想做什麼?你究竟需要什麼幫助?請具體說明。 :) – Imdad

回答

1

從您提供的描述看來,您似乎還沒有完全實現原生Android位置機制所需的內容。 Android中的位置提供程序以異步方式工作,因此您必須註冊一個偵聽程序,以便在生成位置更新時收到通知。 您不能指望系統立即響應(除非您使用getLastKnownLocation(String provider)方法here)。

你的課程包括一個implements LocationListener,它應該強制你實施一系列方法,包括onLocationChanged(Location location)。 這種方法是在獲取位置時將被觸發的方法;您可以檢查location物體以查看其來源(無線或GPS)和其他數據(速度,準確性等)。

看官方指南瞭解更多詳情here。 由於您的調試操作正在處理從環境(GPS和無線網絡)收集的數據,系統的行爲將取決於這些變量。