2011-10-12 72 views
0

我有一個獲取位置並將其發送到服務器的服務,我也有一個使用按鈕啓動和停止服務的活動。當我啓動服務時,所有按鈕都不起作用,並且一段時間後活動部隊關閉,等待或關閉該選項。什麼可能導致這個問題?服務凍結活動?

回答

0

我之前做過類似的事情......我不發佈整個代碼,只是主要的東西。這不會運行,我只是想給你想法,想要什麼和如何處理它。 魔術是在sendUpdatesToUI中完成的...我保存了自己所有不重要的方法,當你實現LocationListener時你會覆蓋 - 你最清楚,你需要哪些。

類:

public class ServiceLocator extends Service implements LocationListener 
public static final String BROADCAST_ACTION = "my.app.isgreat"; 
private final Handler handler = new Handler(); 
private LocationManager locationManager; 
Intent intent; 

public void onCreate() { 
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
    intent = new Intent(BROADCAST_ACTION); 
} 

public void onStart(Intent intent, int startId) { 
    handler.removeCallbacks(sendUpdatesToUI); 
    handler.postDelayed(sendUpdatesToUI, DEBUG_DELAY); 

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
      DEBUG_DELAY, 3, this); 

} 

@Override 
public void onDestroy() { 
    super.onDestroy(); 
    handler.removeCallbacks(sendUpdatesToUI); 
    locationManager.removeUpdates(this); 
    locationManager = null; 

}

//Here is the second thread, that won'z freeze your UI 
//DisplayLogginInfo() sets all the values you wanna send 
private Runnable sendUpdatesToUI = new Runnable() { 
public void run() { 
    DisplayLoggingInfo(); 
    handler.postDelayed(this, DEBUG_DELAY); 
} 

}; 

private void DisplayLoggingInfo() { 
    intent.putExtra("long", String.format("%.4f", lastLocation.getLongitude())); 
    sendBroadcast(intent); 
} 

它可能不會運行方式,因爲我踢了所有的無趣的東西,但它應該給你一個想法,如何將程序一個位置線程,它不會凍結你的用戶界面。

玩得開心