在应用程序完全关闭之前,Android请求服务器

时间:2017-09-06 08:52:24

标签: java android android-intentservice android-ondestroy

我只有一个Activity,当用户关闭应用程序时(从最近的应用程序的os清单中)我想向我的服务器api发送请求并更改用户状态。 所以我创建了IntentService并在我的onDestroy()方法中调用它,但它不起作用。怎么做?还有什么办法可以做到这一点(在应用程序杀死之前向服务器发送请求)? 我的代码:

的活动:

@Override
protected void onDestroy() {
    Intent intent = new Intent(this, MakeOfflineIntentService.class);
    intent.putExtra(Variables.INTENT_TOKEN, Token);
    intent.setAction("ACTION_MAKE_OFFLINE");
    startService(intent);
    super.onDestroy();
}

在我的IntentService中:

public class MakeOfflineIntentService extends IntentService {

private static final String ACTION_MAKE_OFFLINE = "ACTION_MAKE_OFFLINE";

private static final String EXTRA_TOKEN = Variables.INTENT_TOKEN;

public MakeOfflineIntentService() {
    super("MakeOfflineIntentService");
}

public static void startActionFoo(Context context, String param1) {
    Intent intent = new Intent(context, MakeOfflineIntentService.class);
    intent.setAction(ACTION_MAKE_OFFLINE);
    intent.putExtra(EXTRA_TOKEN, param1);
    context.startService(intent);
}

@Override
protected void onHandleIntent(Intent intent) {
    if (intent != null) {
        final String action = intent.getAction();
        if (ACTION_MAKE_OFFLINE.equals(action)) {
            final String param1 = intent.getStringExtra(EXTRA_TOKEN);
            retrofitBaseInformationChange(param1,Variables.OFFLINE,1);
        }
    }
}

private void retrofitBaseInformationChange(final String Token, final int online, int vehicle){
    RetrofitCallServer retrofitCallServer = new RetrofitCallServer(WebServiceUrls.RETROFIT_INFORMATION_CHEETAH_MAN);
    OnCallBackRetrofit onCallBackRetrofit = retrofitCallServer.getResponse();

    Call<OBRbaseInfromationChange> call = onCallBackRetrofit.askBaseInformationChange(Token,online,vehicle);
    call.enqueue(new Callback<OBRbaseInfromationChange>() {

        @Override
        public void onResponse(Call<OBRbaseInfromationChange> call, Response<OBRbaseInfromationChange> response) {
            /*response gotten maybe success or not*/
            if (response.isSuccessful()){
                OBRbaseInfromationChange obr = response.body();
                if(obr.code == 200){
                    Log.i(Variables.APP_TAG,"BaseInformationChange successful");
                }
                else{
                    Log.i(Variables.APP_TAG,"BaseInformationChange error code: "+obr.code);
                }
            }// end if response successful
            else {
                Log.i(Variables.APP_TAG,"BaseInformationChange not Successful: "+response.code());
            }
        }

        @Override
        public void onFailure(Call<OBRbaseInfromationChange> call, Throwable t) {
            /*our request not sent or conversion problem*/
            Log.i(Variables.APP_TAG,"onFailure BaseInformationChange: "+t.getMessage());
        }

    });
}
// end retrofitBaseInformationChange()

}

最后在我的清单中:

<service
        android:name=".Services.MakeOfflineIntentService"
        android:exported="false"
        android:stopWithTask="false"/>

2 个答案:

答案 0 :(得分:2)

您是否尝试在START_STICKY覆盖中返回onStartCommand

发送请求后,您可以致电stopService以阻止自己。

据我所知,即使是粘性服务也可能会重新创建&#34;当你杀了应用程序。也许,Intent不是这里使用的最佳方式。

我在这里SharedPreferences

  • 您应用的onCreate设置密钥&#34; app_offline&#34;到&#34;假&#34;

  • onDestroy将此键设置为&#34; true&#34;并启动服务

  • 服务为START_STICKY,当找到&#34; app_offline&#34;如果是这样,发送请求,更新&#34; app_offline&#34;为false(重置)然后执行自动关闭。

这样的事情。 希望这有助于,欢呼,格里斯

答案 1 :(得分:1)

感谢Grisgram的回答,我解决了这个问题,并在此处粘贴我的代码以获得更完整的答案:

我在SharedPreferences名称IS_APP_CLOSED中创建一个变量。 当应用程序在onCreate中打开时:

saveL.saveInLocalStorage(Variables.IS_APP_CLOSED,false);
    startServiceToMakeOffline();

方法startServiceToMakeOffline()是:

private void startServiceToMakeOffline(){
    Intent intent= new Intent(this, MakeOfflineService.class);
    startService(intent);
}

在此活动的onDestroy中:

@Override
protected void onDestroy() {
    saveL.saveInLocalStorage(Variables.IS_APP_CLOSED,true);
    super.onDestroy();
}

这是我的服务类:

public class MakeOfflineService extends Service {

private boolean isAppClosed = false;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    loadInfoFromLocalStorage();
    if(isAppClosed){
        askServer();
    }

    return Service.START_STICKY;

}

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

private void loadInfoFromLocalStorage() {
    SharedPreferences prefs = getApplicationContext().getSharedPreferences(Variables.CHEETAH_NORMAL, 0);
    isAppClosed     = prefs.getBoolean(Variables.IS_APP_CLOSED, false);
    prefs = null;
}
// end loadInfoFromLocalStorage()


private void askServer() {
    //TODO: request server than when result gotten:
    stopSelf();
}
}

这是我的清单:

<service
        android:name=".Services.MakeOfflineService"
        android:stopWithTask="false"/>