服务中的定期位置更新(Android)

时间:2015-03-10 08:52:51

标签: android android-intent android-service android-pendingintent android-alarms

我正在尝试实现一旦开始一直持续的服务(单元操作系统由于缺乏资源而强行关闭它)。该服务每五分钟获得用户的位置。在我的实现中,如果应用程序发送到后台但在应用程序终止时停止,则服务可以正常工作。

您还可以建议如何定期更新(例如,在5分钟后获取位置)

GeoFenceService.java

public class GeoFenceService extends Service {

private Context mContext;

private List<TestMalls> mTestMalls ;
private MyLocationManager mLocationManager;
private HashMap<Integer, Double> mallDistances;

private ServiceHandler mServiceHandler;
private Looper mServiceLooper;

@Override
public void onCreate(){
    super.onCreate();
    mContext = getBaseContext();

    this.mLocationManager = MyLocationManager.getInstance();
    HandlerThread thread = new HandlerThread("ServiceStartArguments", android.os.Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();

    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
}

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startid){

    Message msg = mServiceHandler.obtainMessage();
    msg.arg1 = startid;
    mServiceHandler.sendMessage(msg);

    return START_STICKY;
}

private final class ServiceHandler extends Handler {

    public ServiceHandler(Looper looper){
        super(looper);
    }

    @Override
    public void handleMessage(Message msg) {

        Toast.makeText(mContext, "Service running ... ", Toast.LENGTH_SHORT).show();

        mLocationManager.startListenLocation(mContext);

        while (mLocationManager.hasLocation()) {

            for (TestMalls t : mTestMalls) {
                mallDistances.put(t.mallId, (double) mLocationManager.distanceInMetersFromLocation(t.latitude, t.longitude));
            }

            Iterator bt = mallDistances.entrySet().iterator();
            while (bt.hasNext()) {
                Map.Entry<Integer, Double> pair = (Map.Entry<Integer, Double>) bt.next();
                Log.v("Hash Map Distances", "Id: " + String.valueOf(pair.getKey()) + " Distance " + String.valueOf(pair.getValue()));
                bt.remove();
            }
        }
    }
}

@Override
public void onDestroy() {
    Log.v("Service", "done - finished");
}
}

1 个答案:

答案 0 :(得分:3)

使用PendingIntent方法创建getService()并将其添加到AlarmManager,每5分钟重复一次。确保Service在完成工作后自行停止(即在结束时致电stopSelf())。

Intent i = new Intent(getApplicationContext(), LocationService.class);
PendingIntent pi = PendingIntent.getService(getApplicationContext(), requestCode, i, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, 0,
            5*60*1000, pi);

假设您的Service正常工作,这将有效。