2010-12-07 70 views
1

我試圖大量使用Location API。我沒有任何問題做一個簡單的活動刷新一個位置監聽器的TextView,沒關係。安卓位置和主題

事情是,我必須把所有的位置的東西放在像主要活動調用的經理類的東西。所以我必須把所有的東西都放在那個班級裏,並且把這個地點告訴活動。這是活動時間:

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState);   
    setContentView(R.layout.main); 
    g = new GPSManager(getApplicationContext()); 
    t = new Thread(g); 
    t.start(); 
    updateWithNewLocation(g.getLocation()); 
}  
private void updateWithNewLocation(Location location) { 
    String latLongString; 
    TextView myLocationText; 
    myLocationText = (TextView)findViewById(R.id.loca); 
    if (location != null) { 
     double lat = location.getLatitude(); 
     double lng = location.getLongitude(); 
     latLongString = "Lat:" + lat + "\nLong:" + lng; 
    } else { 
     latLongString = "No location found"; 
    } 
    myLocationText.setText("Your Current Position is:\n" + 
    latLongString); 
}  

這是「經理人」類:

public GPSManager(Context context) { 
    locationManager = (LocationManager)context.getSystemService(service); 
    String service = Context.LOCATION_SERVICE; 
    Criteria criteria = new Criteria(); 
    criteria.setAccuracy(Criteria.ACCURACY_FINE); 
    criteria.setAltitudeRequired(false); 
    criteria.setBearingRequired(false); 
    criteria.setCostAllowed(true); 
    criteria.setPowerRequirement(Criteria.POWER_LOW); 
    provider = locationManager.getBestProvider(criteria, true); 
} 
public Location getLocation() { 
    return this.location; 
} 
private final LocationListener locationListener = new LocationListener() { 
    public void onLocationChanged(Location location) { 
     Manager.this.location=location; 
    } 
    public void onProviderDisabled(String provider){ 
     locationManager.removeUpdates(this); 
    } 
    public void onProviderEnabled(String provider){ } 
    public void onStatusChanged(String provider, int status, 
     Bundle extras){ } 
    }; 

@Override 
public void run() { 
    Looper.prepare(); 
    locationManager.requestLocationUpdates(provider, 0, 0, 
      locationListener);   
    location = locationManager.getLastKnownLocation(provider); 
    Looper.loop(); 
    Looper.myLooper().quit(); 
} 
private Handler handler = new Handler() { 
@Override 
public void handleMessage(Message msg) { 
    locationManager.removeUpdates(locationListener); 
} 

我的問題是,好了,它不會在所有工作!如果我把這個代碼放在活動中,不涉及任何線程,它很好用。但這樣,它只是說「找不到位置」。我需要讓Manager類始終監聽更改,所以當我詢問當前位置是否更新時。

回答

0

選項#1:刪除「經理」類。

選項2:使「經理」級別爲Service

選項#3:將「經理」類設爲自定義Application

選項#4:用HandlerThread替換Thread

+0

感謝您的回答!刪除管理員類絕對不是一種選擇,但它既不是一個服務也不是一個應用程序,所以使它成爲一個HandlerThread將是最好的解決方案。問題是,我找不到有關如何實現它的任何信息。你能給我一個額外的手嗎?謝謝:) – ferostar 2010-12-07 15:07:53