2011-01-26 215 views
2

目前,我正在尝试开发一个Android应用程序。应用从GPS第一(直通onLocationUpdates(GPS_PROVIDER, 0, 0 , Listener)读取位置数据,如果GPS无法检索我的情况下,5秒)在特定的时间数据(时,又问到Network provider(直通onLocationUpdates(NETWORK_PROVIDER,0,0, Listener))。如何在Android多线程程序中停止looper.loop()?

在我的节目我已经处理。如下这个任务

mWorker = new WorkerThread(); 
mWorker.start(); // Thread creation and Calling run() Method 

class WorkerThread extends Thread{  
public void run() { 
try {  
if(isGPSEnabled){ 

//Call GPS_PROVIDER for Location updates, 
//Will get location value in Location Change Listener 

requestLocationUpdates(GPS_PROVIDER,0,0,Listener); 
Log.d(TAG,"GPS Listener is registered and thread is going for Sleep"); 
Thread.sleep(THREAD_SLEEP_TIME); 

}else if (isNetworkEnbles){ 
// if GPS_PROVIDER is not available, will call to NETWORK_PROVIDER 
// Will get location value to OnLocationChangeListener 

requestLocationUpdates(NETWORK_PROVIDER,0,0,listener); 
Log.d(TAG,"NETWORK Listener is registered and thread is going for Sleep"); 
Thread.sleep(THREAD_SLEEP_TIME); 
} 
} catch (InterruptedException e){ 
    // Thread is interrupted on OnLocationChange Listener 
    // Thread has been Interrupted, It means.. data is available thru Listener. 

} 
// Thread had sleep for THREAD_SLEEP_TIME , but Still data is not available 
If (GPS or Network data isnt available thru GPS listener or Network Listener) { 
    // Do try for one more time. 

} 
} 

现在我OnLocationChanged监听器的代码如下:

public void onLocationChanged(Location location) { 

// Listener got location 
// First Intrupt the sleeping Thread 
mWorker.interrupt(); 

if (loc != null) 
{ 
    //get Location 
} 

} 

现在我的问题是,当我运行这段代码时,Worker Thread从不会调用OnLocationChanged Listener。

我在工作线程中插入looper.Loop(),调用了OnLocationChanged。但它连续运行,并且不会停止。我应该如何停止looper.loop()

是否有任何其他方式通过,我可以管理我的上述任务,除了workerThread. 如果你需要进一步澄清,只是让我知道。

+0

你为什么要在单独的线程中运行这个? – getekha 2011-01-26 15:03:44

回答

0

请勿在主线程上使用Thread.sleep()。你阻止它运行。你不需要为你正在做的事情建立一个单独的线程,你只需要让你的主线程继续运行,这样你就可以在收到事件时通过你的回调来处理事件。