我有一个获取位置并将其发送到服务器的服务,我也有一个用按钮启动和停止服务的活动。当我启动服务时,所有按钮都不起作用,一段时间后,活动强制关闭,提供等待或关闭的选项。可能导致问题的原因是什么?
答案 0 :(得分:0)
之前我做过类似的事情...我不发布整个代码,主要是jsut。这不会运行,我只想给你一个想法,什么是llok以及如何处理它。 魔术是在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);
}
它可能不会那样运行,因为我踢出了所有无趣的东西,但它应该给你一个想法,如何编程一个位置线程,这不会冻结你的UI。
玩得开心