Currently, I am trying to develop an Android application. Application reads Location data from GPS
first(thru onLocationUpdates(GPS_PROVIDER, 0, 0 , Listener)
and if GPS
is not able to retrieve data in specific time ( in my case 5 sec ),it again asks to Network provider
( thru onLocationUpdates(NETWORK_PROVIDER,0,0, Listener)
).
In my program I have handled this task as follows.
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 reg开发者_如何学编程istered 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.
}
}
Now My OnLocationChanged Listener code as Follows:
public void onLocationChanged(Location location) {
// Listener got location
// First Intrupt the sleeping Thread
mWorker.interrupt();
if ( loc != null )
{
//get Location
}
}
Now my problem is , when I run this code , Worker Thread never calls OnLocationChanged
Listener.
I have inserted looper.Loop()
in worker thread , OnLocationChanged
is called. But it runs continuously and looper
not get stop. How should I stop looper.loop()
?
Is there any other way thru which I can manage my above task except workerThread.
If you need more clarification, just let me know.
Don't use Thread.sleep() on the main thread. You are blocking it from running. There is no need to have a separate thread for what you are doing, you just need to allow your main thread to continue running so that you can handle the events through your callbacks as they are received.
精彩评论