我遇到了与此处提出的问题类似的问题: Sending message to a Handler on a dead thread when getting a location from an IntentService
我在 IntentService 中放置了一个 LocationListener,我听说这是一个不好的放置位置,因为监听器在onHandleIntent()
完成后被销毁。
我的意图服务根据 GPS 和网络提供商检查最后一个已知位置。我正在寻找一种在检查用户所在位置之前“唤醒” GPS 和网络定位器的方法。
IntentService 每分钟运行一次,它每 5-30 分钟检查一次更新的位置。有没有办法requestLocationUpdates
在实际位置检查之前设置一个我可以调用的方法?
12-31 14:09:33.664: W/MessageQueue(3264): Handler (android.location.LocationManager$ListenerTransport$1) {41403330} sending message to a Handler on a dead thread
12-31 14:09:33.664: W/MessageQueue(3264): java.lang.RuntimeException: Handler (android.location.LocationManager$ListenerTransport$1) {41403330} sending message to a Handler on a dead thread
12-31 14:09:33.664: W/MessageQueue(3264): at android.os.MessageQueue.enqueueMessage(MessageQueue.java:196)
12-31 14:09:33.664: W/MessageQueue(3264): at android.os.Handler.sendMessageAtTime(Handler.java:473)
12-31 14:09:33.664: W/MessageQueue(3264): at android.os.Handler.sendMessageDelayed(Handler.java:446)
12-31 14:09:33.664: W/MessageQueue(3264): at android.os.Handler.sendMessage(Handler.java:383)
12-31 14:09:33.664: W/MessageQueue(3264): at android.location.LocationManager$ListenerTransport.onLocationChanged(LocationManager.java:193)
12-31 14:09:33.664: W/MessageQueue(3264): at android.location.ILocationListener$Stub.onTransact(ILocationListener.java:58)
12-31 14:09:33.664: W/MessageQueue(3264): at android.os.Binder.execTransact(Binder.java:338)
12-31 14:09:33.664: W/MessageQueue(3264): at dalvik.system.NativeStart.run(Native Method)
预定服务
public class ScheduledService extends IntentService {
private LocationManager lm;
LocationListener locationListener;
public ScheduledService() {
super("ScheduledService");
}
@Override
protected void onHandleIntent(Intent intent) {
lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
lm.removeUpdates(this);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
if(isNetworkAvailable()) {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
try {
Location lastKnownLocation = getBestLocation();
double lat = lastKnownLocation.getLatitude();
double lon = lastKnownLocation.getLongitude();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}