背景服务在某些设备中不起作用,比如vivo,mi等。应用程序从最近的应用程序中清除后

时间:2017-08-25 13:24:15

标签: service background

我使用以下代码将位置发送到服务器,但是在应用程序从最近的应用程序中清除后,它在某些设备中无效。那么什么是应用关闭时启动服务的最佳替代方式。

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

    private static final String TAG = "LocationActivity";
    private static final long INTERVAL = 1000 * 10;
    private static final long FASTEST_INTERVAL = 1000 * 5;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mCurrentLocation;
    String mLastUpdateTime;
    private LocationCallback mLocationCallback;

    SharePref sharePref;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("sevice start", ">>>>>>>>>>>>>>>>>>>>>>>>>......");
        sharePref = new SharePref(GpsService.this);

        Intent notificationIntent = new Intent(this, MainActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);

        Notification notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_logo)
                .setContentTitle("My Awesome App")
                .setContentText("Doing some work...")
                .setContentIntent(pendingIntent).build();

        startForeground(1337, notification);

        createLocationRequest();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                for (Location location : locationResult.getLocations()) {
                    // Update UI with location data
                    // ...
                    Toast.makeText(getBaseContext(), locationResult.toString(), Toast.LENGTH_LONG).show();
                }
            }

            ;
        };

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("sevice start", "mGoogleApiClient >>>>>>>>>>>>>>>>>>>>>>>>>......");
        mGoogleApiClient.connect();

        return START_REDELIVER_INTENT;
    }

    @Override
    public void onDestroy() {

        mGoogleApiClient.disconnect();
        super.onDestroy();
    }

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

    //Check Google play is available or not


    @Override
    public void onConnected(Bundle bundle) {
        startLocationUpdates();

    }

    @Override
    public void onConnectionSuspended(int i) {
    }


    @Override
    public void onLocationChanged(Location location) {
        //Save your location
        Log.e("GpsService Location lat", "Is change " + location.getLatitude());
        Log.e("Gps Location long", "Is change " + location.getLongitude());
        Log.e("GpsService userid", "Enter" + sharePref.getUserId());

        Toast.makeText(GpsService.this, location.toString(), Toast.LENGTH_LONG).show();

        sharePref.SetLat(String.valueOf(location.getLatitude()));
        sharePref.SetLong(String.valueOf(location.getLongitude()));

        String lati = String.valueOf(location.getLatitude());
        String longi = String.valueOf(location.getLongitude());

        HashMap<String, String> param = new HashMap<>();
        param.put(PARAM_USER_ID, sharePref.getUserId());
        param.put(PARAM_SESSION_ID, sharePref.getSessionId());
        param.put(PARAM_LAT, lati);
        param.put(PARAM_LONG, longi);
        param.put(PARAM_PLATFORM, PLATFORM);

        BikerService.addLatLong(GpsService.this, param, new APIService.Success<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {

                Log.e("Location Response-->", "" + response.toString());
                BikerParser.AddLatLongResponse AddLatLongResponse = BikerParser.AddLatLongResponse.addLatLongResponse(response);
                if (AddLatLongResponse.getStatusCode() == API_STATUS_FOUR_ZERO_ONE) {
                    stopService(new Intent(GpsService.this, GpsService.class));
                }

            }
        });

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    }

    protected void startLocationUpdates() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Log.e("sevice start", "startLocationUpdates >>>>>>>>>>>>>>>>>>>>>>>>>......");
        PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

        Log.d(TAG, "Location update started ..............: ");

    }

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        Log.d(TAG, "Location update stopped .......................");
    }


}

0 个答案:

没有答案