【问题标题】:Android Request to server before application compeletly closed在应用程序完全关闭之前向服务器发出 Android 请求
【发布时间】:2017-09-06 08:52:24
【问题描述】:

我只有一个 Activity ,当用户关闭应用程序(从操作系统清除最近应用程序列表)时,我想向我的服务器 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"/>

【问题讨论】:

    标签: java android android-intentservice android-ondestroy


    【解决方案1】:

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

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

    据我所知,即使是粘性服务也可能在您终止应用时“重新创建”。所以也许,Intent 不是在这里使用的最佳方式。

    我会选择SharedPreferences

    • 您应用的onCreate 将键“app_offline”设置为“false”

    • onDestroy 将此键设置为“true”并启动服务

    • 服务是START_STICKY,当它发现“app_offline”为真时,发送它的请求,将“app_offline”更新为假(重置它),然后执行自关闭。

    类似的东西。 希望这会有所帮助,干杯,格里斯

    【讨论】:

    • 我之前没用过START_STICKY,我google一下试试。谢谢
    • 感谢您的帮助我那天解决了它,它有帮助,现在我在这里复制我的一些代码以获得更完整的答案
    【解决方案2】:

    感谢 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"/>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-18
      • 1970-01-01
      • 2023-01-31
      • 2021-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多