关闭UI线程的Android GPS回调

我无法让GPS的onLocationChanged在另一个线程上运行。 我理解如何在调用函数时管理UI线程,但是使用GPS时,我不会主动调用该函数。

我的意图是每次GPS接收到读数时闪烁。 我把这个函数放在Runnable中。 我将此函数传递给实现LocationListener的类。 然后在主类中,我启动了一个调用requestLocationUpdates的新线程。 我希望LocationListener的onLocationChanged将在不同的线程中运行,发布到回调并在UI线程中进行必要的UI效果。 不幸的是,每次尝试调用requestLocationUpdates时程序都会崩溃。 这样做的正确方法是什么?

现在它看起来像这样

主要课程:

final Runnable changeLight = new Runnable(){ public void run(){ // do stuff } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.capture); status = (ImageView) findViewById(R.id.status); database = new DatabaseManager(this); new Thread(){ public void run(){ location = (LocationManager) getSystemService(LOCATION_SERVICE); listener = new GPSManager(database, changeLight, light, status); location.requestLocationUpdates("gps", 10000L, 0, listener); } }.start(); } 

LocationListener类:

 public void onLocationChanged(Location location) { if (location.getAccuracy() <= 32.0){ light = lightColors.Green; status.post(callback); database.insertData(location); } else{ light = lightColors.Yellow; status.post(callback); } } 

exception说无法在未调用Looper.prepare()的线程内创建处理程序

调用location.requestLocationUpdates的线程必须有一个Looper(参见此处 )。 您可以使用HandlerThread而不是Thread。

我遇到了同样的问题。 解决方案结果是,您希望从位置管理器接收位置更新的新线程必须是Looper线程。 为此,您应该做的就是在线程的run()函数中添加以下行。

Looper.prepare();

Looper.loop();

您的问题可能是由主线程的不正确同步引起的吗? 在应用崩溃之前你有任何例外吗? 你能发布符合sscce.org的例子吗?

通常,当您在GUI上处理异步事件时,您应该进行适当的同步: http : //developer.android.com/resources/articles/painless-threading.html