2

在定位应用程序上工作。当在后台服务中更改位置时,我想从 fusedlocation 提供程序获取用户位置。

我的服务在每个时间间隔都给了我位置,但我想要位置改变时的位置不是每个时间间隔

我的服务在重新启动时开始。并在我设置的每个间隔上获取位置。但是我想要位置改变时的位置(用户移动到新位置),而不是每个时间间隔,

public class BacLocSerUme extends Service implements ConnectionCallbacks,
        OnConnectionFailedListener, LocationListener {

    protected static final String TAG = "sanu location services";

    // parameters for the GoogleApiClient Location Request

    private static final long INTERVAL = 1000 * 60;
    private static final long FASTEST_INTERVAL = 1000 * 5;
    private static final long ONE_MIN = 1000 * 60;
    private static final long REFRESH_TIME = ONE_MIN * 5;
    private static final float MINIMUM_ACCURACY = 50.0f;

    // in it for Api params
    private LocationRequest locationRequest;
    private GoogleApiClient googleApiClient;
    private FusedLocationProviderApi fusedLocationProviderApi = LocationServices.FusedLocationApi;
    private Location mlocation;

    // Flag that indicates if a request is underway.
    private boolean mInProgress;
    private Boolean servicesAvailable = false;

    IBinder mBinder = new LocalBinder();

    public class LocalBinder extends Binder {
        public BacLocSerUme getServerInstance() {
            return BacLocSerUme.this;
        }

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return mBinder;
    }

    // On create Method to init all the value of request of playservices

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();

        Log.i(TAG, "on create of service");
        mInProgress = false;
        buildGoogleApiClient();
        servicesAvailable = servicesConnected();

    }

    private Boolean servicesConnected() {

        // Check that Google Play services is available
        int resultCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(this);
        // If Google Play services is available
        if (ConnectionResult.SUCCESS == resultCode) {

            return true;
        } else {

            return false;
        }

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        Log.i(TAG, "on start of services");
        super.onStartCommand(intent, flags, startId);
        if (!servicesAvailable || googleApiClient.isConnected() || mInProgress)
            return START_STICKY;
        setUpLocationClientIfNeeded();

        if (googleApiClient.isConnected() || !googleApiClient.isConnecting()
                && !mInProgress) {
            Log.i(TAG, "Services Started from service class");
            mInProgress = true;
            googleApiClient.connect();
        }

        return START_STICKY;

    }

    private void setUpLocationClientIfNeeded() {
        if (mlocation == null) {
            buildGoogleApiClient();

        }

    }

    // Building GoogleApiClient
    private void buildGoogleApiClient() {
        Log.i(TAG, "Building GoogleApiClient");
        googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API).addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).build();

        createLocationRequest();

    }

    // Building Request for googleApiClient
    private void createLocationRequest() {
        locationRequest = new LocationRequest();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(INTERVAL);
        locationRequest.setFastestInterval(FASTEST_INTERVAL);
        Log.i(TAG, "location request created");
    }

    // This Followins two mathod is generated by implements of
    // connectioncallback
    // on connected and on connection suspend
    // this is used for connection call back//// check connected or not

    @Override
    public void onConnected(Bundle connectionHint) {
        Log.i(TAG, "Connected to GoogleApiClient");

        mlocation = fusedLocationProviderApi.getLastLocation(googleApiClient);
        if (mlocation == null) {
            fusedLocationProviderApi.requestLocationUpdates(googleApiClient,
                    locationRequest, this);
        }

        Intent intent = new Intent(this, LocationReceiver.class);
        PendingIntent locationIntent = PendingIntent.getBroadcast(
                getApplicationContext(), 14872, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        fusedLocationProviderApi.removeLocationUpdates(googleApiClient,
                locationIntent);

    }

    @Override
    public void onConnectionSuspended(int cause) {
        Log.i(TAG, "Connection suspended");
        googleApiClient.connect();

    }

    // generated from inplementation from OnConnectionFailedListener
    @Override
    public void onConnectionFailed(ConnectionResult result) {
        mInProgress = false;
        Log.i(TAG, "Location Services fails. ");

        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
                + result.getErrorCode());

    }

    // method generated from requestlocation listener
    @Override
    public void onLocationChanged(Location location) {

        mlocation = location;

        Log.i(TAG, "Location Changed");
        appendLog(DateFormat.getDateTimeInstance().format(new Date())
                + ": location changed" + mlocation.getLatitude(),
                Constants.LOG_FILE);
        Toast.makeText(this, "Locatiopn Changed", Toast.LENGTH_LONG).show();

    }

    // ondestroid method of services
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        mInProgress = false;

        if (servicesAvailable && googleApiClient != null) {
            fusedLocationProviderApi.removeLocationUpdates(googleApiClient,
                    this);
            // Destroy the current location client
            googleApiClient = null;
        }

        super.onDestroy();
    }

    // extra methods for utill

    public String getTime() {
        SimpleDateFormat mDateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        return mDateFormat.format(new Date());
    }

    public void appendLog(String text, String filename) {
        File logFile = new File(filename);
        if (!logFile.exists()) {
            try {
                logFile.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try {
            // BufferedWriter for performance, true to set append to file flag
            BufferedWriter buf = new BufferedWriter(new FileWriter(logFile,
                    true));
            buf.append(text);
            buf.newLine();
            buf.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}// End of main services
4

1 回答 1

0

您可以使用 ResultReceiver 执行此操作。参考链接:如何将消息从服​​务发送到活动

使用更改位置时只需发送一些消息

resRec.send(object,null);
于 2015-08-10T09:04:09.937 回答