在Android上的后台运行GPS监听器

Dev*_*Dev 7 service gps android

我想知道当Android应用程序在后台时如何接收GPS.有没有完整的教程来解释它?

Sid*_*rth 5

您需要使用AlarmManager激活挂起的意图(通过广播接收器)以启动后台服务。

一些适合您的示例代码

在您的MainActivity中

AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent notifyintent = new Intent(this, OnAlarmReceiver.class);
notifyintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
notifyintent.setAction("android.intent.action.NOTIFY");
PendingIntent notifysender = PendingIntent.getBroadcast(this, 0, notifyintent,
        PendingIntent.FLAG_UPDATE_CURRENT);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 20 * 1000,
        notifysender);
Run Code Online (Sandbox Code Playgroud)

AlarmReceiver类

public class OnAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    // PullPendingRequests.acquireStaticLock(context)
    try {
        lock = getLock(context);
        lock.acquire();
        context.startService(new Intent(context, UpdateCustomerRequests.class));
    } finally {
        if (lock.isHeld()) {
            lock.release();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

广播接收器

private static final String NAME = "com.commonsware.cwac.wakeful.WakefulIntentService";
private static volatile PowerManager.WakeLock lockStatic = null;
private static PowerManager.WakeLock lock;

// Needed since network will to work when device is sleeping.
synchronized private static PowerManager.WakeLock getLock(Context context) {
    if (lockStatic == null) {
        PowerManager mgr = (PowerManager) context.getSystemService(Context.POWER_SERVICE);

        lockStatic = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, NAME);
        lockStatic.setReferenceCounted(true);
    }

    return (lockStatic);
  }
}
Run Code Online (Sandbox Code Playgroud)

后台服务。在这里,您会注意到2个要点

  1. WakeLock,以确保您的设备在后台唤醒并使用网络
  2. 用于LocationManager的黑客。我不得不调试了大约2个星期,相信我,您需要这个。requestLocationUpdates和getLastKnownLocation只会在需要时不提供您的位置。因此,AlarmManager(比Java TimerTask运行得更好)。

所有这些都可以在Play商店的生产应用中使用。

public class UpdateCustomerRequests extends IntentService implements LocationListener {
private static Context mainContext;

public UpdateCustomerRequests() {
    super("UpdateCustomerRequests");
    mHandler = new Handler();
    me = this;
}

public static UpdateCustomerRequests getService() {
    if (me == null)
        me = new UpdateCustomerRequests();
    return me;
}

@Override
final protected void onHandleIntent(Intent intent) {
    mainContext = getApplicationContext();
    Location myLocation;

    if (HomeScreen.getLocationManager() != null) {
        // this is needed to trigger a background location change. Since LocationManager does not work on Samsung phones. Its a hack needed.
        HomeScreen.getLocationManager().requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER, 0, 0, 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(final Location location) {
            }
        });
        myLocation = HomeScreen.getLocationManager().getLastKnownLocation(
                LocationManager.NETWORK_PROVIDER);
        if (myLocation != null)
            onLocationChanged(myLocation);
        else {
            God.notifications.setSpeedNotification();
        }
    } else
        Log.e("Taxeeta:PullPendingRequets", "Not activated");

}

@Override
public void onLocationChanged(final Location location) {
    // Do your background stuff
}

}
Run Code Online (Sandbox Code Playgroud)

最后,不要忘记您的明显事情。

 <service
        android:name="com.taxeeta.UpdateCustomerRequests"
        android:enabled="true"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:theme="@android:style/Theme.Light.NoTitleBar" />

    <receiver
        android:name="com.taxeeta.support.OnAlarmReceiver"
        android:exported="true" >
        <intent-filter>
            <action android:name="android.intent.action.NOTIFY" />
        </intent-filter>
    </receiver>
    <receiver
        android:name="com.taxeeta.HomeScreen$ResponseReceiver"
        android:exported="true" >
        <intent-filter>
            <action android:name="com.taxeeta.intent.action.GET_SCREEN_UPDATES" />
        </intent-filter>
    </receiver>
Run Code Online (Sandbox Code Playgroud)


Kar*_*ana 0

您可以使用始终在后台运行的服务。在后台服务中,您可以获得当前的纬度和经度,并且可以使用 Android 地理编码器类进一步将这些纬度和经度转换为正确的位置...检查以下链接:

http://www.codeproject.com/KB/android/GPSLocator.aspx

  • 谢谢,但是这个代码是用于活动的,我如何使用该服务。 (2认同)