如何编写Android服务无限期运行并利用位置服务

时间:2014-08-20 06:54:49

标签: android android-service

我是Android服务的新手,并且已经在线阅读了一些教程,特别是Vogalla的教程。我的应用程序旨在当用户以速度移动时停止工作> 10公里。但为了让它再次工作,用户必须静止超过180秒。要检测这种情况,必须保持后台服务运行以跟踪时间。以下是我的代码 -

package com.opaxlabs.text;

import android.app.Service;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

public class MyService extends Service implements LocationListener {
    private LocationManager manager;
    private String provider;
    private Location location;
    private double lat;
    private double lng;
    private float speed;
    private boolean stationary=false;
    private Handler h;
    private long lastFix=System.currentTimeMillis();

    public MyService() {

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("My Service command started", "My Service command started");
//      return super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

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

    @Override
    public void onCreate() {
        LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
        boolean enabled = service
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (!enabled) {
            Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(settingsIntent);
        }
        manager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        provider = manager.getBestProvider(criteria, false);
        location = manager.getLastKnownLocation(provider);
        manager.requestLocationUpdates(provider, 180, 0, this);
        h=new Handler();
        h.postDelayed(new Runnable() {

            @Override
            public void run() {
                long current=System.currentTimeMillis();
                if(current-lastFix>180000){
                    stationary=true;
                    standing();
                }
                h.postDelayed(this, 1800);
            }
        }, 1800);
//      lastFix=System.currentTimeMillis();

        Log.i("My Service created", "My Service created");
        super.onCreate();
    }

    @Override
    public void onLocationChanged(Location location) {
        lat = location.getLatitude();
        lng = location.getLongitude();
        speed = location.getSpeed();
        if(speed>10.0){
            travelling();
            lastFix=System.currentTimeMillis();
        }
        stationary=false;
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    public boolean isStationary(){
        return stationary;
    }

    private void travelling(){
        Intent intent=new Intent("Travelling");
        sendMotionBroadcast(intent);
    }

    private void standing(){
        Intent intent=new Intent("Standing");
        sendStationaryBroadcast(intent);
    }

    private void sendStationaryBroadcast(Intent intent){
        intent.putExtra("stationary", isStationary());
        intent.putExtra("lat", lat);
        intent.putExtra("lng", lng);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

    private void sendMotionBroadcast(Intent intent){
        intent.putExtra("speed", speed);
        intent.putExtra("lat", lat);
        intent.putExtra("lng", lng);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        Log.i("My Service started", "My Service started");
        super.onStart(intent, startId);
    }

    @Override
    public void onDestroy() {
        Log.i("My Service stopped", "My Service stopped");
        super.onDestroy();
    }


}

但我发现这里有问题。每次我的应用程序运行时,似乎都会调用onCreate()。这样我就失去了之前保存的lastFix,并且无法可靠地确定用户是否静止超过180秒。是否每次运行应用程序时都会重新创建服务?我在这做错了什么? 请帮我提一下你的建议。提前致谢。 编辑: 我在应用程序上执行了一些测试,发现onCreate()每次都被调用但不是onDestroy()所以可能没有重新创建服务但是调用onCreate()会导致重置变量。再次感谢。

2 个答案:

答案 0 :(得分:0)

如果你想避免重新创建服务,那么你可以试试这个黑客

步骤1在全局MyService服务中创建一个静态布尔变量

步骤2 onStartCommand检查是否为真/假,并且你可以采取决定

答案 1 :(得分:0)

您可以使用SharedPreferences保存lastFix变量,然后使用" onCreate"加载并使用它。