最好的方法是使用 CWAC 的定位服务
Location Poller 服务已经为我们提供了使用它,只需给出唤醒它的时间间隔
像这样做,你将需要 jar 文件,你可以从中获取它https://www.dropbox.com/sh/pgxk2v9l5vl0h2j/3svyZnuwOK/CWAC-LocationPoller.jar
从您的活动中启动 LocationPoller 并将闹钟设置为您想要的重复时间
AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent i = new Intent(this, LocationPoller.class);
Bundle bundle = new Bundle();
LocationPollerParameter parameter = new LocationPollerParameter(bundle);
parameter.setIntentToBroadcastOnCompletion(new Intent(this,
LocationReceiver.class));
// try GPS and fall back to NETWORK_PROVIDER
parameter.setProviders(new String[] { LocationManager.GPS_PROVIDER,
LocationManager.NETWORK_PROVIDER });
parameter.setTimeout(120000);
i.putExtras(bundle);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), 300000, pi);
创建一个接收器类 Location Receiver,从中获取经纬度
public class LocationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try {
Bundle b=intent.getExtras();
LocationPollerResult locationResult = new LocationPollerResult(b);
Location loc=locationResult.getLocation();
String msg;
if (loc==null) {
loc=locationResult.getLastKnownLocation();
if (loc==null) {
msg=locationResult.getError();
}
else {
msg="TIMEOUT, lastKnown="+loc.toString();
}
}
else {
msg=loc.toString();
Log.i("Location Latitude", String.valueOf(loc.getLatitude()));
Log.i("Location Longitude", String.valueOf(loc.getLongitude()));
Log.i("Location Accuracy", String.valueOf(loc.getAccuracy()));
}
Log.i(getClass().getSimpleName(), "received location: " + msg);
}
catch (Exception e) {
Log.e(getClass().getName(), e.getMessage());
}
}
并将其添加到您的清单中
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<receiver android:name="com.commonsware.cwac.locpoll.LocationPoller" />
<service android:name="com.commonsware.cwac.locpoll.LocationPollerService" />
以及接收者声明,您将在其中获取所有内容
<receiver android:name="com.RareMediaCompany.Helios.LocationReceiver" />