【发布时间】:2013-09-27 15:02:18
【问题描述】:
我的应用有问题。我的应用程序实际上是一项服务。我有 Main extends Service,它有私有 Looper looper 变量来获取 HandlerThread looper。在onCreate 函数中,我初始化位置管理器、位置侦听器和 HandlerThread(将其循环器设置为循环器变量),然后我尝试使用requestLocationUpdates 将循环器变量作为循环器传递。我得到一个错误
09-22 17:30:24.069: E/AndroidRuntime(1414): Caused by: java.lang.IllegalArgumentException: looper==null
我应该对这个 HandlerThread 做其他事情吗?也许开始吧?:>
我没有粘贴任何代码,因为它很长,而且我不知道适合解决问题的相关部分。因此,我很乐意传递您可能需要的任何代码(HandlerThread?还有其他吗?)
感谢您的帮助。
** 编辑 **
好的,onCreate函数:
public void onCreate() {
super.onCreate();
Log.d("Service", "Service onCreate starts");
running = true;
lt = new LooperThread("GPSIntentLT");
serviceLocationM = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
serviceLocationL = new MyLocationListener();
requestUpdates(serviceLocationL);
Log.d("Service", "Service onCreate ends");
}
requestUpdates 函数(上面调用,出现错误):
private void requestUpdates(LocationListener listener)
{
Log.d("Service", "requestUpdates starts");
serviceLocationM.removeUpdates(listener);
flag = displayGpsStatus();
switch(flag)
{
case 0:
Log.d("Service", "No Location Provider");
break;
case 1:
Log.d("Service", "Network Provider");
serviceLocationM.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10, 25, listener, theLooper);
break;
case 2:
Log.d("Service", "GPS Provider");
serviceLocationM.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 25, listener, theLooper);
break;
}
Log.d("Service", "requestUpdates ends");
}
和HandlerThread:
private class LooperThread extends HandlerThread{
public LooperThread(String name) {
super(name);
Log.d("Service", "LooperThread constructor starts");
theLooper = getLooper();
Log.d("Service", "LooperThread constructor ends");
}
@Override
public void run() {
super.run();
Log.d("Service", "LooperThread run called");
}
}
最后,这个应用程序的 logcat:
09-22 18:21:47.997: D/Service(386): Service onCreate starts
09-22 18:21:47.997: D/Service(386): LooperThread constructor starts
09-22 18:21:48.007: D/Service(386): LooperThread constructor ends
所以它确实在 requestLocationUpdates 函数上失败了,它发生在 2.2 模拟器上,在 2.3.3 上它通过杀死它的进程(?)来崩溃整个模拟器。
【问题讨论】:
-
您至少应该发布类、onCreate 和处理程序线程的代码。
-
@Jems 添加了代码。
-
你为什么要扩展一个HandlerThread?
-
得到它的looper :> 这是我被告知的最后一个问题的答案。还有其他方法吗? (我需要让我的应用保持持久/循环,因此它每 5~ 分钟获取一次位置并对其进行处理)。
-
调用 ht = new HandlerThread(); ht.start(); handler = new Handler(ht.getLooper())
标签: android android-service android-2.2-froyo looper