android - 实现计时器以获取 gps 位置

标签 android gps countdowntimer

我想从 gps 获取位置。由于 gps 需要一些时间来获取位置,所以我需要添加一个 倒计时器。如果时间到期想从网络中获取位置。 我是 android 和 java 的初学者,我按照以下方式实现,但我没有成功。 请清除我的错误或提供任何示例代码。提前致谢。

if (isGPSEnabled) { 
        CountDownTimer countDownTimer = new CountDownTimer(1000, 3000); 
        {
            public void onTick(long millisUntilFinished) {

                 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,time,distance, this);
                 Log.d("GPS Enabled", "GPS Enabled");
                 if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                 if (location != null) {
                       Latitude =  location.getLatitude();
                       Longitude =  location.getLongitude();

                         String Text =  " From GPS: latitude = " + Latitude +" longitude = " + Longitude + " Device Id: " + device_id;
                         SmsManager smsManager = SmsManager.getDefault();
                         smsManager.sendTextMessage(phoneNo, null, Text, null, null);
                         Log.i("Send SMS", "");
                         this.abortBroadcast();
                   }
                }
            }

       public void onFinish() {
            if(locationManager == null)
                {
                   locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,time,distance, this);
               Log.d("Network", "Network");
               if (locationManager != null) {
               location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
               if (location != null) {
               Latitude  =    location.getLatitude();
               Longitude =    location.getLongitude();
               String Text =  " From Network: latitude = " + Latitude +" longitude = "  + Longitude+ " Device Id: " + device_id;
                   SmsManager smsManager = SmsManager.getDefault();
               try{
                  smsManager.sendTextMessage(phoneNo, null, Text, null, null);
                  Log.i("Send SMS", "");
          this.abortBroadcast();           
          } catch (Exception e) {
           e.printStackTrace(); }
   }

最佳答案

public void turnGPSOn() {

        String provider = Settings.Secure.getString(getContentResolver(),
                Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        if (!provider.contains("gps")) {
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings",
                    "com.android.settings.widget.SettingsAppWidgetProvider");
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("3"));
            sendBroadcast(poke);
        }
    }


private class MyTimerTask extends TimerTask {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // code to get and send location information
                    locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                    if (!locManager
                            .isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                        turnGPSOn();
                    }

                    try {
                        locManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER, 1000, 10,
                                locationListener);

                    } catch (Exception ex) {
                        turnGPSOff();
                    }

                }

            });
        }
    }

    private void updateWithNewLocation(Location location) {
        String latLongString = "";
        try {
            if (location != null) {

                Log.e("test", "gps is on send");
                latitude = Double.toString(location.getLatitude());
                longitude = Double.toString(location.getLongitude());

                Log.e("test", "location send");

                locManager.removeUpdates(locationListener);


                latLongString = "Lat:" + latitude + "\nLong:" + longitude;
                Log.w("CurrentLocLatLong", latLongString);
            } else {
                latLongString = "No location found";
            }
        } catch (Exception e) {
        }

    }

    private final LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            updateWithNewLocation(location);
        }

        public void onProviderDisabled(String provider) {
            updateWithNewLocation(null);
        }

        public void onProviderEnabled(String provider) {
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    };

Calling the timer :

long gpsTimeInterval=2000;
void startTimer()
{

myTimer = new Timer();
                                myTimerTask = new MyTimerTask();
                                myTimer.scheduleAtFixedRate(myTimerTask, 0,
                                        gpsTimeInterval);
}

关于android - 实现计时器以获取 gps 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27074425/

相关文章:

android - WebRTC android-PeerConnectionFactory.createPeerConnection 始终返回 null

android - 使用 MediaCodec 录制 720p 视频但编码视频的 fps 太低

Android:后台服务中的计时器

安卓:CountDownTimer 不工作

javascript - 在 jQuery 倒数计时器中更改日期

android - 如何使用 Firebase 推送消息取决于用户在设备上的帐户状态

C# - LINQ - GPS经纬度的最短距离

android - 如何通过 latlng 获得两点之间的距离?

android - CountdownTimer:当用户返回上一个 Activity 时,如何从剩余时间重新开始?

javascript - 在 Android 数字上运行的 Java web 应用程序