When no GPS fix found, the code is getting stuck indefinitely in the looper. I want to add a timeout so that if there is no GPS fix found, it should come out of the looper and execute the remaining part of the code.
I will really appreciate if you can help me in fixing this issue.
public class service_task extends Service {
@SuppressLint("MissingPermission")
@Override
public void onCreate() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
private class ServerThread extends Thread implements LocationListener {
public LocationManager locationManager = null;
public String msg = "default";
public String id = "default";
private Location mLocation = null;
public Socket socket = null;
public int serviceid;
public ServerThread(LocationManager locationManager, int startid) {
super("UploaderService-Uploader");
this.locationManager = locationManager;
this.serviceid=startid;
}
@SuppressLint("MissingPermission")
public void run() {
Looper.prepare();
this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
Looper.loop();
if (mLocation!=null) {
msg = "GPS data:" + mLocation;
}else{
msg ="No GPS data";
}
stopSelf(serviceid);
}
@Override
public void onLocationChanged(Location location) {
mLocation = location;
Log.d("D", String.valueOf(location));
this.locationManager.removeUpdates(this);
Looper.myLooper().quit();
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
}
@SuppressLint("MissingPermission")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("D", "startcommand");
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
ServerThread thread = new ServerThread(locationManager,startId);
thread.start();
return START_REDELIVER_INTENT;
}
}
Create a Handler
that uses your Looper
: handler = new Handler(Looper.myLooper());
Then use handler.postDelayed(Runnable, long)
to post a new Runnable
that cancels location updates and quits your Looper
after a given delay.