Service 后台服务在某些设备(如维梧、mi等)中不起作用。。从最近的应用程序中清除应用程序后

Service 后台服务在某些设备(如维梧、mi等)中不起作用。。从最近的应用程序中清除应用程序后,service,background,Service,Background,我正在使用下面的代码将位置发送到服务器,但在从最近的应用程序中清除应用程序后,它在某些设备中不起作用。那个么,当应用程序关闭时,启动服务的最佳替代方式是什么呢 public class GpsService extends Service implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private static

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

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 .......................");
    }


}
公共类GpsService扩展服务实现LocationListener、GoogleAppClient.ConnectionCallbacks、GoogleAppClient.OnConnectionFailedListener{
私有静态最终字符串TAG=“LocationActivity”;
专用静态最终长间隔=1000*10;
专用静态最终最长最快_间隔=1000*5;
位置请求mLocationRequest;
GoogleapClient MGoogleapClient;
位置mCurrentLocation;
字符串mLastUpdateTime;
私有位置回调mLocationCallback;
SharePref SharePref;
@凌驾
public void onCreate(){
super.onCreate();
日志.e(“服务启动”、“>>>>>>>>>>>>>>>>>>>>>>>>……”;
sharePref=新的sharePref(GpsService.this);
Intent notificationIntent=新的Intent(this,MainActivity.class);
PendingEvent PendingEvent=PendingEvent.getActivity(此,0,
通知意图,0);
Notification Notification=新建NotificationCompat.Builder(此)
.setSmallIcon(R.drawable.ic_标志)
.setContentTitle(“我最棒的应用程序”)
.setContentText(“正在做一些工作…”)
.setContentIntent(pendingIntent).build();
startForeground(1337,通知);
createLocationRequest();
mgoogleapclient=新的Googleapclient.Builder(此)
.addApi(LocationServices.API)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.build();
mlLocationCallback=新位置Callback(){
@凌驾
public void onLocationResult(LocationResult LocationResult){
对于(位置:locationResult.getLocations()){
//使用位置数据更新用户界面
// ...
Toast.makeText(getBaseContext(),locationResult.toString(),Toast.LENGTH_LONG.show();
}
}
;
};
}
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
日志.e(“服务启动”、“mGoogleApiClient”>>>>>>>>>>>>>>>>>>>……”;
mGoogleApiClient.connect();
返回启动\u重新交付\u意图;
}
@凌驾
公共空间{
mGoogleApiClient.disconnect();
super.ondestory();
}
@可空
@凌驾
公共IBinder onBind(意向){
返回null;
}
//检查Google play是否可用
@凌驾
未连接的公共空间(捆绑包){
startLocationUpdates();
}
@凌驾
公共空间连接暂停(int i){
}
@凌驾
已更改位置上的公共无效(位置){
//保存您的位置
Log.e(“GpsService Location lat”,“Is change”+Location.getLatitude());
Log.e(“Gps位置长”、“是更改”+位置.getLongitude());
Log.e(“GpsService userid”,“输入”+sharePref.getUserId());
Toast.makeText(GpsService.this,location.toString(),Toast.LENGTH_LONG.show();
SetLat(String.valueOf(location.getLatitude());
sharePref.SetLong(String.valueOf(location.getLongitude());
String-lati=String.valueOf(location.getLatitude());
String longi=String.valueOf(location.getLongitude());
HashMap param=新的HashMap();
参数put(param_USER_ID,sharePref.getUserId());
param.put(param_SESSION_ID,sharePref.getSessionId());
参数put(参数LAT,lati);
参数put(参数长、长);
参数put(参数平台,平台);
BikerService.addLatLong(GpsService.this、param、new-APIService.Success()){
@凌驾
成功时公共无效(JSONObject响应){
Log.e(“位置响应-->”,“”+Response.toString());
BikerParser.AddLatLongResponse AddLatLongResponse=BikerParser.AddLatLongResponse.AddLatLongResponse(响应);
if(AddLatLongResponse.getStatusCode()==API\u状态\u四个\u零个\u一个){
stopService(新意图(GpsService.this,GpsService.class));
}
}
});
}
@凌驾
public void onconnection失败(@NonNull ConnectionResult ConnectionResult){
}
受保护的void startLocationUpdates(){
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS\u FINE\u LOCATION)!=PackageManager.permission\u已授予和&ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS\u LOCATION)!=PackageManager.permission\u已授予){
考虑到呼叫
//ActivityCompat#请求权限
//在此处请求缺少的权限,然后覆盖
//public void onRequestPermissionsResult(int-requestCode,字符串[]权限,
//int[]格兰特结果)
//处理用户授予权限的情况。请参阅文档
//对于ActivityCompat,请请求权限以获取更多详细信息。
返回;
}
Log.e(“服务启动”、“startLocationUpdates>>>>>>>>>>>>>>>>>>>>>>……”;
Pendingreult Pendingreult=LocationServices.FusedLocationApi.requestLocationUpdates(mgoogleapClient,mlLocationRequest,this);
Log.d(标记“位置更新已开始…”);
}
受保护的void createLocationRequest(){
mlLocationRequest=新位置请求();
mlLocationRequest.setInterval(间隔);
mLocationRequest.SetFastTestInterval(最快间隔);
mLocationRequest.setPriority(位置请求.PRIORITY\u高精度