当我们从最近的应用中清除应用时,服务将停止工作?

时间:2016-10-14 05:29:26

标签: android service android-intentservice

当我们从最近的应用中清除应用时,服务会停止工作吗?因为当我在代码下运行时。要在位置发生变化时更新lat,lng。当我从最近的应用程序中清除应用程序时,位置更新将停止。当我看到正在运行的应用程序视图时,服务处于运行状态。请清楚地了解服务将如何正常工作。谢谢进展。

  public class GPSTracker extends Service implements
    ConnectionCallbacks,
    OnConnectionFailedListener,
    LocationListener, GooglePlayServicesClient.ConnectionCallbacks {

public static final long UPDATE_INTERVAL = 5000;
public static final long FASTEST_INTERVAL = 1000;

private LocationClient mLocationClient;
private LocationRequest mLocationRequest;
private boolean mInProgress;
private boolean servicesAvailable = false;
DatabaseHandler db;
@Override
public void onCreate() {
    super.onCreate();

    mInProgress = false;
    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)

       .setInterval(UPDATE_INTERVAL) // Set the update interval to 5 seconds
      .setFastestInterval(FASTEST_INTERVAL); // Set the fastest update interval to 1 second

    servicesAvailable = servicesConnected();
    setUpLocationClientIfNeeded();
     db = new DatabaseHandler(this);
}

private boolean servicesConnected() {
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    return ConnectionResult.SUCCESS == resultCode;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    Log.d("TAG", "onLocationChanged onStart Command");
    if (!servicesAvailable || mLocationClient.isConnected() || mInProgress)
        return START_STICKY;

    setUpLocationClientIfNeeded();

    if (!mLocationClient.isConnected() || !mLocationClient.isConnecting() && !mInProgress) {
        mInProgress = true;
        mLocationClient.connect();
    }

    return START_STICKY;
}

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

  @Override
   public void onDestroy() {
 /*   mInProgress = false;
    if (servicesAvailable && mLocationClient != null) {
        mLocationClient.removeLocationUpdates( this);
        mLocationClient = null;
    }
   */
    super.onDestroy();
}

private void setUpLocationClientIfNeeded() {
    if (mLocationClient == null)
        mLocationClient = new LocationClient(this, this, this);
}

/*
 * LocationListener Callbacks
 */

@Override
public void onLocationChanged(Location location) {
    //Carnival.updateLocation(location);
    Log.d("TAG", "onLocationChanged " + location.getLongitude());
    Log.d("Insert: ", "Inserting ..");
    db.addContact(new Contact("" + location.getTime(), " Latitude " + location.getLatitude() + " Longitude " + location.getLongitude()));

}



/*
* GooglePlayServicesClient Callbacks
*/

@Override
public void onConnected(Bundle bundle) {
    if (mLocationClient != null) {
        mLocationClient.requestLocationUpdates(mLocationRequest, this);
    }
}

@Override
public void onDisconnected() {

}

@Override
public void onConnectionSuspended(int i) {

}



@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    mInProgress = false;
    /*
    * Google Play services can resolve some errors it detects.
    * If the error has a resolution, try sending an Intent to
    * start a Google Play services activity that can resolve
    * error.
    */
    if (!connectionResult.hasResolution()) {
        // If no resolution is available, display an error dialog
    }
}
}

3 个答案:

答案 0 :(得分:1)

常规Service不足以确保系统在他/她从最近列表中清除我们的应用时不会杀死它。

出于特定目的,告诉系统您希望Service作为foreground运行:

  

前台服务是一种被认为是某种东西的服务   用户积极地意识到并因此不是系统的候选者   要杀...

您可以在Service

中调用此方法
    Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text), System.currentTimeMillis());
    Intent notificationIntent = new Intent(this, ExampleActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    notification.setLatestEventInfo(this, getText(R.string.notification_title),
        getText(R.string.notification_message), pendingIntent);

    startForeground(ONGOING_NOTIFICATION_ID, notification);

如您所见,startForeground()Notification作为其参数之一。最终,它会设置persistent notification来通知用户您的Service当前正在后台运行。

在对此进行了更多研究之后,似乎使Service前景不足以确保其在这样的条件下持续存在。

当我们的应用程序从“最近”列表中删除时,会有一个解决方法是监听,并通过这样做明确地从那里重新启动Service

    @Override 
    public void onTaskRemoved(Intent rootIntent){
         Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());

         PendingIntent restartServicePendingIntent = PendingIntent.getService(
         getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
         AlarmManager alarmService = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
         alarmService.set(ELAPSED_REALTIME, elapsedRealtime() + 1000, restartServicePendingIntent);

         super.onTaskRemoved(rootIntent); 
    }

当然,您必须在清单上的Service声明中添加适当的标记(请参阅Max Rockwood's answer)。

答案 1 :(得分:0)

您需要在清单中设置stopWithTask=false以进行服务。

这样的事情:

<service
    android:enabled="true"
    android:name=".MyService"
    android:stopWithTask="false" />

它会阻止服务停止,如果我们要执行任何可以对其进行操作的操作,如果我们从最近清除应用程序,则会调用方法onTaskRemoved()

答案 2 :(得分:0)

有一个名为OnStartCommand()的事件覆盖它并在该函数中再次调用该活动