void startGPSThread() { Thread t = new Thread() { LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); boolean isDebug = CurrentLogEntry.getInstance().isDebug(); // Define a listener that responds to location updates LocationListener locationListener = new LocationListener() { public void onStatusChanged(String provider, int status, Bundle extras) { /* This is called when the GPS status changes */ String tag = "onStatusChanged, "; switch (status) { case LocationProvider.OUT_OF_SERVICE: Log.w(tag, "Status Changed: Out of Service"); break; case LocationProvider.TEMPORARILY_UNAVAILABLE: Log.w(tag, "Status Changed: Temporarily Unavailable"); break; case LocationProvider.AVAILABLE: break; } } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { // This is called if the GPS is disabled in settings. // Bring up the GPS settings Intent intent = new Intent( android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); } public void onLocationChanged(Location location) { // Once a location has been received, ignore all other position // updates. locationManager.removeUpdates(locationListener); locationManager.removeUpdates(this); // Make sure that the received location is a valid one, // otherwise show a warning toast and hit "back". if (location == null) { String warningString = "Location was unititialized!"; if (isDebug) { Toast.makeText(getApplicationContext(), warningString, Toast.LENGTH_LONG).show(); } KeyEvent kev = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK); onKeyDown(KeyEvent.KEYCODE_BACK, kev); } CurrentLogEntry.getInstance().setUserLatitude(location.getLatitude()); CurrentLogEntry.getInstance().setUserLongitude(location.getLongitude()); //Send update to the main thread int result = 0; if (location.getLatitude() == 0 || location.getLongitude() == 0) { result = -1; } messageHandler.sendMessage(Message.obtain(messageHandler, result)); } }; @Override public void run() { locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, locationListener); // Wait until a position has bee acquired. while(!CurrentLogEntry.getInstance().isReadyToCalculate()){ try { wait(250); } catch (InterruptedException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } } }; t.start(); }
Running GPS positioning in a background thread on Android
最新推荐文章于 2024-09-02 18:19:21 发布