/**
* Created by Parag on 01/05/2017.
*/
public class AppService extends android.app.Service {
public static final String TAG=AppService.class.getName();
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle=intent.getExtras();
if(bundle!=null){
final String logout=bundle.getString("logout");
final String driverLoginId=bundle.getString("driverLoginId");
if(logout!=null&&driverLoginId!=null){
Toast.makeText(this, "logging out", Toast.LENGTH_SHORT).show();
Log.e(TAG,"Logging out");
Log.e(TAG,"Inside driverLogout "+driverLoginId);
Call<LogoutResponse> call = RestHandler.getApiService().driverLogout(driverLoginId);
call.enqueue(new Callback<LogoutResponse>() {
@Override
public void onResponse(Call<LogoutResponse> call, Response<LogoutResponse> response) {
//close the service on receiving response from API
Log.e("Response : ",response.body().getStatus()+"");
AppService.this.stopSelf();
}
@Override
public void onFailure(Call<LogoutResponse> call, Throwable t) {
//close the service on receiving response from API
AppService.this.stopSelf();
}
});
}else{
//Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
Log.e(TAG,"DriverLoginId : "+driverLoginId);
Log.e(TAG,"Logout : "+logout);
}
}else{
//Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
Log.e(TAG,"Service Start");
}
return super.onStartCommand(intent,flags,startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
Log.e(TAG,"Service Stop");
UserLocalStore userLocalStore=new UserLocalStore(AppService.this);
Log.e("USER DATA :",userLocalStore.fetchUserData().toString());
Intent restartServiceTask = new Intent(getApplicationContext(),this.getClass());
restartServiceTask.setPackage(getPackageName());
restartServiceTask.putExtra("logout","true");
restartServiceTask.putExtra("driverLoginId",userLocalStore.fetchUserData().getUserId());
PendingIntent restartPendingIntent =PendingIntent.getService(getApplicationContext(), 1,restartServiceTask, PendingIntent.FLAG_ONE_SHOT);
AlarmManager myAlarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
myAlarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartPendingIntent);
super.onTaskRemoved(rootIntent);
}
}
我也面临同样的问题,无法从 onTaskRemoved 方法进行任何 API 调用。
所以,我也研究了很多,但没有找到解决方案。所以,我终于有了重新启动 Web 服务的想法,并在意图中放置了一些额外的内容。通过这种方式,您可以区分服务何时重新启动以执行 API 调用。