Running GPS positioning in a background thread on Android
16lz
2022-07-24
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();}
更多相关文章
- 代码中设置drawableleft
- android 3.0 隐藏 系统标题栏
- Android开发中activity切换动画的实现
- Android(安卓)学习 笔记_05. 文件下载
- Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
- 技术博客汇总
- android 2.3 wifi (一)
- AndRoid Notification的清空和修改
- Android中的Chronometer