2010-07-06 80 views
2

我无法让GPS的onLocationChanged在不同的线程上运行。我知道如何在我调用一个函数但使用GPS时管理UI线程,但我不主动调用该函数。Android GPS回调关闭UI线程

我的意图是每次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); 
     } 
    } 

异常说无法创建内螺纹已不叫尺蠖处理程序.prepare()

回答

2

,你叫location.requestLocationUpdates必须有一个活套螺纹(见here)。 您可以使用HandlerThread而不是Thread。

1

我遇到了同样的问题。解决方案原来是,您想从位置管理器接收位置更新的新线程必须是Looper线程。要做到这一点,你所要做的就是在线程的run()函数中加入以下几行代码。

Looper.prepare();

Looper.loop();