【发布时间】:2023-03-13 16:45:01
【问题描述】:
我需要做什么才能让我的 LocationListener 触发它的 onLocationChanged 方法?
我是这个东西的新手(java 和 android)。这就是我正在做的事情。 我通过调用 context.startService(serviceIntent); 来处理位置请求。 在意图服务中,我有一个嵌套类来充当 LocationListener 在 onHandleIntent 方法中,我启动了一个请求位置更新的线程 我在 OnHandleIntent 方法中维护了对 LocationListener 对象和踏板的引用。
我的计划是让 onLocationChanged 方法更新一个变量,我可以定期检查以查看更新是否已完成,然后跳出循环并对该位置执行一些操作。
问题是永远不会调用 onLocationChanged 方法。 LocationListener 对象在 onHandleIntent 方法结束之前仍然有效。 我什至可以直接调用它并获得我期望的调试消息。 我很确定 DDMS 正在更改位置,因为我已将其打印在各种调试日志中并且我看到它正在更改。
代码如下:
package com.example.locationrequestreceiver;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
public class LocationRequestService extends IntentService {
private LocationManager locationManager;
public class UpdateHandler implements Runnable, LocationListener {
@Override
public void onLocationChanged(Location arg0) {
Log.d("myStuff", "inside location changed");
}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
@Override
public void onProviderDisabled(String provider) {}
@Override
public void run() {
// TODO Auto-generated method stub
Looper.prepare();
Log.d("myStuff", "inside thread");
locationManager.requestLocationUpdates("gps", 0, 0, this);
Log.d("myStuff", "run ending");
Looper.loop() // <--- this was the fix
}
}
public LocationRequestService() {
super("LocationRequrestService");
Log.d("myStuff", "inside the service");
}
@Override
protected void onHandleIntent(Intent arg0) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
UpdateHandler update_handler = new UpdateHandler();
Thread update_handler_thread = new Thread(update_handler);
Log.d("myStuff", "starting thread");
update_handler_thread.start();
for (int count = 0; count < 20; count++) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
Location location = locationManager.getLastKnownLocation("gps");
update_handler.onLocationChanged(location);
}
}
【问题讨论】: