【问题标题】:Service will stop working when we clear the app from recent apps?当我们从最近的应用程序中清除应用程序时,服务将停止工作?
【发布时间】:2016-10-14 05:29:25
【问题描述】:

当我们从最近的应用程序中清除应用程序时,服务是否会停止工作?因为当我在代码下面运行时。要在位置更改时更新 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
    }
}
}

【问题讨论】:

  • 你有return START_STICKY 所以即使它被杀死的系统也会重新启动
  • 我返回 START_STICKY 检查上面的代码

标签: android service android-intentservice


【解决方案1】:

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

出于特定目的,告诉系统您希望Serviceforeground 运行:

前台服务是被认为是某种东西的服务 用户主动意识到,因此不是系统的候选者 杀死……

您可以通过在 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); 
    }

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

【讨论】:

    【解决方案2】:

    您需要在服务清单中设置stopWithTask=false

    类似这样的:

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

    它可以防止服务停止,如果我们从最近的应用程序中清除应用程序,如果你想执行任何可以覆盖它的操作,就会调用 onTaskRemoved() 方法。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-12-05
        • 2018-11-10
        • 1970-01-01
        • 2015-05-29
        • 1970-01-01
        • 2015-01-06
        • 1970-01-01
        相关资源
        最近更新 更多