创建一个应用程序,可以选择获取位置信息,即使它没有运行

syn*_*nic 2 android

即使应用程序未运行,创建定期获取位置的应用程序(通过GPS或手机信号塔等)的最佳方法是什么?

我的第一个想法是使用AlarmManager以指定的间隔唤醒并检查.我想知道是否有更具体的API可供使用.

Pen*_*m10 8

您订阅了获取LocationChanged的通知.您将获得一个唤醒您的应用程序的广播接收器.您可以使用传递的上下文作为启动点从BroadCast接收器启动活动.

locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

// loop through all providers, and register them to send updates
List<String> providers = locMan.getProviders(false);
for (String provider : providers) {
    Log.e("mytag", "registering provider " + provider);
    long minTimeMs = 5 * 60 * 1000;// 5 minute
    float minDistance = LOCATION_HOT_RADIUS_IN_METERS;
    locMan.requestLocationUpdates(provider, minTimeMs, minDistance,
            getIntent());
}

private PendingIntent getIntent() {
    Intent intent = new Intent(this, LocationReceiver.class);
    return PendingIntent.getBroadcast(
            getApplicationContext(), 0, intent, 0);
}
Run Code Online (Sandbox Code Playgroud)

和接收器

public class LocationReceiver extends BroadcastReceiver {

/*
 * (non-Javadoc)
 * 
 * @see android.content.BroadcastReceiver#onReceive(android.content.Context,
 * android.content.Intent)
 */
@Override
public void onReceive(Context context, Intent intent) {
    try {
        Bundle b = intent.getExtras();
        Location loc = (Location) b
                .get(android.location.LocationManager.KEY_LOCATION_CHANGED);
        if (loc != null) {


        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}
}
Run Code Online (Sandbox Code Playgroud)