关闭申请

时间:2016-05-17 07:12:06

标签: android

我在我的Android应用程序中使用Service,即使我的应用程序未运行,也会通过Fused Location Provider连续获取位置更新。但问题是,只要我的应用程序正在运行,Service正在运行,并且当我关闭我的应用程序时Service也会在某个时间后停止。那么请帮忙吗?

开始服务

Intent startServiceIntent = new Intent(getApplicationContext(), LocationDetector.class);
startService(startServiceIntent);

服务代码:

package com.example.jahanzebahmed.smartlocator;

import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.ContextCompat;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;



public class LocationDetector extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    Location mLastLocation;
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    static String lat=null, lon=null;
    static boolean enableNotifications = false;
    static boolean enableEmails = false;


    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        enableNotifications = true;
        if(!MainActivity.notifications_switch.isChecked())
            MainActivity.notifications_switch.setChecked(true);
        buildGoogleApiClient();
    }


    synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mGoogleApiClient.connect();
        return Service.START_NOT_STICKY;
    }


    @Override
    public void onConnected(Bundle bundle) {
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(5000); // Update location every se
        mLocationRequest.setFastestInterval(5000);
        mLocationRequest.setSmallestDisplacement(0);
        if ((Build.VERSION.SDK_INT >= 23) && (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null) {
            lat = String.valueOf(mLastLocation.getLatitude());
            lon = String.valueOf(mLastLocation.getLongitude());
        }
        checkForNotification();
    }


    @Override
    public void onLocationChanged(Location location) {
        lat = String.valueOf(location.getLatitude());
        lon = String.valueOf(location.getLongitude());
        checkForNotification();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        mGoogleApiClient.disconnect();
        enableEmails = false;
        enableNotifications = false;
        stopSelf();
    }


    void checkForNotification() {
        Location location = new Location("fused");
        location.setLatitude(new Double(lat));
        location.setLongitude(new Double(lon));
        if(enableNotifications)
            new CheckReminders(getApplicationContext()).execute(location);
        if(enableEmails)
            new EmailsHandler(getApplicationContext()).execute(location);
    }


    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        buildGoogleApiClient();
    }


    @Override
    public void onConnectionSuspended(int i) {

    }

}

1 个答案:

答案 0 :(得分:0)

检查:

public class LocationUpdate extends Service implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener {

private static final String TAG = "SERVICE CLASS";
private GoogleApiClient mGoogleApiClient;
// A request to connect to Location Services
private LocationRequest mLocationRequest;

private LocationListener locationListener;
//public  MapsActivity mapsActivity;

public static String latitude;
public static String longitute;
public static String s;

private static final int REQUEST_CODE_LOCATION = 2;

private static double kph = 3.6;
private double speed = 0.0;

/*public LocationUpdate(MapsActivity mapsActivity) {
    this.mapsActivity=mapsActivity;
}*/

private class LocationListener implements com.google.android.gms.location.LocationListener {

    @Override
    public void onLocationChanged(Location location) {

        latitude = String.valueOf(location.getLatitude());
        longitute = String.valueOf(location.getLongitude());
        Log.d("location lat",location.getLatitude()+"");
        Log.d("location long",location.getLongitude()+"");
    }
}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //  Log.e(TAG, "onStartCommand");
    super.onStartCommand(intent, flags, startId);
    boolean stopService = false;
    if (intent != null)
        stopService = intent.getBooleanExtra("stopservice", false);

    System.out.println("stopservice " + stopService);

    locationListener = new LocationListener();
    if (stopService)
        stopLocationUpdates();
    else {
        if (!mGoogleApiClient.isConnected())
            mGoogleApiClient.connect();
    }
    return START_STICKY;
}

@Override
public void onCreate() {
    //  Log.e(TAG, "onCreate");
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API).addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this).build();
}

@Override
public void onDestroy() {
    //  Log.e(TAG, "onDestroy");
    super.onDestroy();
}

public void stopLocationUpdates() {
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, locationListener);
    if (mGoogleApiClient.isConnected())
        mGoogleApiClient.disconnect();
}


@Override
public void onConnectionFailed(ConnectionResult arg0) {
    // TODO Auto-generated method stub
}

@Override
public void onConnected(Bundle arg0) {
    // TODO Auto-generated method stub
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setSmallestDisplacement(10);
    mLocationRequest.setInterval(3000);
    mLocationRequest.setFastestInterval(3000);
    startLocationUpates();
}

private Location startLocationUpates() {

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!=
            PackageManager.PERMISSION_GRANTED) {

    } else {
        // Locatiossssssssn permission has been granted, continue as usual.
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, locationListener);
        //  Log.i("update location","Start update location"+myLocation.getLongitude());
    }
    s = String.valueOf(LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient));

    return LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}

@Override
public void onConnectionSuspended(int arg0) {
    // TODO Auto-generated method stub
}

这将在应用关闭时更新位置。