2011-07-29 93 views
1

我是Android開發人員中的新人。 我正在嘗試管理活動之間的gps位置。特別是我創建了一個線程,從主要活動開始,在幾秒之後更新gps位置並將新位置保存到共享Bean中。 現在,當我將額外的Bean傳遞給下一個活動時,我可以獲取該bean的最後一個值,但是新活動上的bean不會被該線程更新。我不創建一個新的Bean,因此我認爲在新的活動中會看到bean的更新。 有,我用它來獲取額外的新的活動代碼:Android:更新活動間的bean信息

ShareBean pos; 
    Intent intent = getIntent(); 
    Bundle extras = getIntent().getExtras(); 
    if (extras != null) 
    { 
     pos = (ShareBean)intent.getSerializableExtra("Location"); 
    } 

任何幫助是讚賞。 感謝您的進步。 Simone

回答

0

您應該使用LocationManager對象來獲取和訪問位置更新。您可以查詢最近的已知位置以進行快速更新。

關鍵的是,我要求位置管理員開始傾聽,然後從那裏我可以隨時要求快速更新。我將更新的位置信息存儲在我的ApplicationContext對象中(我在本地稱爲appModel),該對象在對象的整個生命週期中都是持久的。

我使用LocationManager這樣的:

locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
startListening(); 

開始聽這個樣子的:

public void startListening() { 

    if (gpsLocationListener == null) { 
     // make new listeners 
     gpsLocationListener = new CustomLocationListener(LocationManager.GPS_PROVIDER); 

     // request very rapid updates initially. after first update, we'll put them back down to a much lower frequency 
     locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 200, gpsLocationListener); 
    } 

    //get a quick update 
    Location networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 

    //this is the applicationContext object which persists for the life of the applcation 
    if (networkLocation != null) { 
     appModel.setLocation(networkLocation); 
    } 
} 

你位置監聽器看起來是這樣的:

private class CustomLocationListener implements LocationListener { 

    private String provider = ""; 
    private boolean locationIsEnabled = true; 
    private boolean locationStatusKnown = true; 

    public CustomLocationListener(String provider) { 
     this.provider = provider; 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     // Called when a new location is found by the network location provider. 
     handleLocationChanged(location); 
    } 

    public void onStatusChanged(String provider, int status, Bundle extras) { 
    } 

    public void onProviderEnabled(String provider) { 
     startListening(); 
    } 

    public void onProviderDisabled(String provider) { 
    } 
} 

private void handleLocationChanged(Location location) { 

    if (location == null) { 
     return; 
    } 

    //get this algorithm from: http://developer.android.com/guide/topics/location/obtaining-user-location.html 
    if (isBetterLocation(location, appModel.getLocation())) { 
     appModel.setLocation(location); 
     stopListening(); 
    } 
} 

祝你好運!