如何在Android中定期获取GPS位置

8
我正在编写一个应用程序,每十分钟记录一次新的GPS位置。
我曾经尝试使用位置轮询器、将位置监听器放在服务中以及将位置监听器放在活动中,但这些方法均无法满足我的需求。
我需要一种方法,在开始记录位置数据之前,让GPS定位监听器提前2分钟启动(以便GPS有充分的时间来查找位置或确定是否没有信号)。我一直通过使用闹钟调用我的gpsActivity来实现这一点。在我调用updatelocation类之前,我的updatelocation类会提取gpsActivity的位置管理器并从中提取位置。
理论上,这应该可以正常工作,但是当我在手机上测试时,总是得到错误的数据(精度太低或根本没有信号)。
如果有人能帮我解决问题,我将不胜感激。
谢谢!
闹钟会在更新位置之前2分钟调用此类。
public class GPSActivity extends Activity {

    public static LocationListener loc_listener = null;
    public static LocationManager locationManager = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        getGPS();
    }

    public static void getGPS() {
        if (loc_listener == null) {
            loc_listener = new LocationListener() {

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

                @Override
                public void onProviderEnabled(String provider) {}

                @Override
                public void onProviderDisabled(String provider) {}

                @Override
                public void onLocationChanged(Location location) {}
            };
        }
        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, 0, 0, loc_listener);
    }

    public static void killGPS() {
        if (locationManager != null && loc_listener != null) {
            locationManager.removeUpdates(loc_listener);
        }
    }
}

两分钟后,该服务将被调用。
public class UpdateLocation extends IntentService {

    public static final String id = "";
    public static int retryCount = 0;
    int notificationID = 1;
    // gets the location manager from the GPSActivity
    LocationManager locationManager = GPSActivity.locationManager;

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public UpdateLocation() {
        super("UpdateLocation");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        locationManager = GPSActivity.locationManager;
        SharedPreferences prefs = getSharedPreferences("Settings", 0);
        final String id = prefs.getString("ID", "");
        HttpParams httpParams = new BasicHttpParams();
        // 30seconds and it stops
        HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
        HttpConnectionParams.setSoTimeout(httpParams, 30000);
        DefaultHttpClient httpclient = new DefaultHttpClient(httpParams);
        HttpPost httpost = new HttpPost(
                "http://iphone-radar.com/gps/gps_locations");
        JSONObject holder = new JSONObject();
        try {
            holder.put("id", id);
            Location location = getLocation();
            if (location != null && (location.getAccuracy() < 25)) {
                retryCount = 0;
                Calendar c = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat(
                        "hh:mmaa MM/dd/yyyy");
                holder.put("time", sdf.format(c.getTime()));
                holder.put("time_since_epoch",
                        System.currentTimeMillis() / 1000);
                holder.put("lat", location.getLatitude());
                holder.put("lon", location.getLongitude());
                StringEntity se = new StringEntity(holder.toString());
                httpost.setEntity(se);
                httpost.setHeader("Accept", "application/json");
                httpost.setHeader("Content-type", "application/json");
                ResponseHandler responseHandler = new BasicResponseHandler();
                String response = httpclient.execute(httpost,
                        responseHandler);
                org.json.JSONObject obj;
                obj = new org.json.JSONObject(response);
                SimpleDateFormat sdf2 = new SimpleDateFormat(
                        "yyyy-MM-dd hh:mm:ssaa");
                addHistory(
                        sdf2.format(c.getTime()),
                        "Background GPS",
                        "Latitude: "
                            + String.format("%.6g%n",
                                    location.getLatitude())
                            + "\n"
                            + "Longitude: "
                            + String.format("%.6g%n",
                                    location.getLongitude()));
                SharedPreferences.Editor editor = prefs.edit();
                editor.putString("LastUpdatedTime", sdf.format(c.getTime()));
                editor.commit();
                Intent setAlarm = new Intent(UpdateLocation.this,
                        UpdateLocation.class);
                PendingIntent pendingIntent = PendingIntent.getService(
                        UpdateLocation.this, 0, setAlarm, 0);
                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(System.currentTimeMillis());
                int UPDATE_TIME = prefs.getInt("Update_time", 10);
                calendar.add(Calendar.MINUTE, UPDATE_TIME);
                alarmManager.set(AlarmManager.RTC_WAKEUP,
                        calendar.getTimeInMillis(), pendingIntent);
                // sets an alarm for the next time we need to record a
                // location
                GPSActivity.killGPS();
                // turns off the gps location listener
                Intent setAlarm2 = new Intent(UpdateLocation.this,
                        GPSActivity.class);
                PendingIntent pendingIntent2 = PendingIntent.getService(
                        UpdateLocation.this, 0, setAlarm2, 0);
                Calendar calendar2 = Calendar.getInstance();
                calendar2.add(Calendar.MINUTE, UPDATE_TIME - 2);
                alarmManager.set(AlarmManager.RTC_WAKEUP,
                        calendar2.getTimeInMillis(), pendingIntent2);
                // sets an alarm to turn on the gpsActivity 2mins before the
                // next time updatelocation needs to record some data
            }
        } finally {
        }
    }
}

尝试这个可行的演示:http://tinyurl.com/942lhyf - user1468129
1个回答

4

使用接收器和服务组合在一起。为此,您可以在此链接中找到一个完整的示例。其中包含一个监听器,您可以在活动中使用该监听器来通知您新位置已准备就绪。


https://dev59.com/yHE85IYBdhLWcg3wbTD2 看起来有所不同。它推荐使用闹钟管理器。 - Mawg says reinstate Monica

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接