2011-04-14 31 views
1

我跟在http://developer.android.com/guide/topics/location/obtaining-user-location.html上,並且在onCreate方法中處於活動狀態時工作正常。將Android應用程序中的GPS功能外包給一個單獨的類

然後我想將這個功能外包給名爲LocationHelper的單獨的類。

import android.content.Context; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 

public class LocationHelper { 

public Context mContext; 
public Location loc; 

public LocationHelper (Context mContext){ 
    this.mContext = mContext; 

    // Acquire a reference to the system Location Manager 
    LocationManager locationManager = (LocationManager)  mContext.getSystemService(Context.LOCATION_SERVICE); 

    // Define a listener that responds to location updates 
    LocationListener locationListener = new LocationListener() { 
     public void onLocationChanged(Location location) { 
      // Called when a new location is found by the network location provider. 
      setLocation(location); 
     } 

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

     public void onProviderEnabled(String provider) {} 

     public void onProviderDisabled(String provider) {} 
     }; 

    // Register the listener with the Location Manager to receive location updates 
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); 
} 

public void setLocation(Location location) { 
    this.loc = location; 
} 

public Location getLocation() { 
    return this.loc; 
} 
} 

在活動中,我這樣做;基本上我想從我的幫助類中拉出(用於測試目的!)GPS座標並顯示它。問題在於,該位置始終爲空。

public class GraffitiWall extends Activity { 

private TextView tv; 

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

    tv = new TextView(this); 

    LocationHelper gpsie = new LocationHelper(this); 
    while (true){ 
     makeUseOfNewLocation(gpsie.getLocation()); 
    } 
} 

public void makeUseOfNewLocation(Location loc){ 
    if (loc == null){return;} 
    tv.setText("" + loc.getLatitude()); 
    setContentView(tv); 
} 
} 

我在想什麼,做錯了什麼?

回答

0

在你的onCreate方法中放入一個無限循環是不好的想法。您的問題很可能是由於onCreate從未完成並將控制權交還給操作系統而導致的。如果這導致強制關閉錯誤,我不會感到驚訝。

也許你需要做的是創建一個服務,這將做你的位置監測並從那裏更新你的活動。

+0

我做了一些日誌記錄,發現LocationHelper-class中的loc是** always ** null,這在將相同的代碼放在activity中時不會發生。 – mhk 2011-04-14 12:19:01

+0

但這可能是因爲您的上下文尚未完全初始化,因爲您沒有將控制權交還給Android。 – 2011-04-14 12:24:28

+0

我沒有做到這一點,而(真)......也不工作。 – mhk 2011-04-14 12:27:03

相關問題