Android在onDestroy中发送HTTP Post请求

huangapple go评论105阅读模式
英文:

Android send HTTP Post in onDestroy

问题

为了我的应用程序,我只需要一种简单的方法将数据同步到服务器。我目前不需要担心任何响应。我认为只需要在主活动的onDestroy中启动一个服务就可以了,但由于某种原因,服务从未被创建。难道不可能从onDestroy中使用意图附加项来创建新的服务吗?根据我所调试的情况,变量从未被放入捆绑包中。以下是我的onDestroy()代码:

Intent intent = new Intent(this, CustomService.class);
Bundle extras = intent.getExtras();
extras.putString(Variables.REFRESH_TOKEN_KEY, apiGateway.getTokens().getRefreshToken());
extras.putString(Variables.ID_TOKEN_KEY, apiGateway.getTokens().getIdToken());
try {
    extras.putString(RequestFields.CustomObject, new ObjectMapper().writeValueAsString(CustomObject.asMap()));
} catch (JsonProcessingException e) {
    e.printStackTrace();
}
startService(intent);

我不能像我想的那样进行盲目请求(不使用服务,因为这似乎太过复杂),因为显然不能在主UI线程上进行网络请求。想知道是否有更好的方法可以进行这种盲目请求,甚至不使用服务,从而避开我目前在启动服务方面遇到的问题。

英文:

So for my app I just need a simple way of syncing data to a server. I do not need to worry about any response (at least for now). I thought it would be as simple as just starting a service from the onDestroy of my main activity but for some reason the service is never being created. Is it not possible to make new services from the onDestroy with intent extras? From what I've been able to debug, the variables are never being put into the bundle. Below is my code for my onDestroy().

    Intent intent = new Intent(this, CustomService.class);
    Bundle extras = intent.getExtras();
    extras.putString(Variables.REFRESH_TOKEN_KEY, apiGateway.getTokens().getRefreshToken());
    extras.putString(Variables.ID_TOKEN_KEY, apiGateway.getTokens().getIdToken());
    try {
        extras.putString(RequestFields.CustomObject, new ObjectMapper().writeValueAsString(CustomObject.asMap()));
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    startService(intent);

I can't just make the blind request like I would like to (without a service since it seems like overkill) since obviously you can't make network requests on the main UI thread. Wondering if there's a better way of doing such a blind request without even using a service thus bypassing my problem right now with not being able to start it in the first place.

答案1

得分: 0

你可以使用java.util.concurrent API,如果你需要另一种解决方案。Executors非常方便且易于使用。

顺便提一下onDestroy()的javadoc中写道:
> 注意:不要指望会调用这个方法来保存数据!例如,如果一个Activity正在编辑内容提供者中的数据,那些编辑应该在onPause()或onSaveInstanceState(Bundle)中提交,而不是在这里。我认为可能会出现onDestroy从未被调用的情况。

但是在onPause中也要注意:
> 当Activity B在Activity A前面启动时,会在A上调用此回调。只有在A的onPause()返回后,B才会被创建,因此确保不要在这里做任何耗时的操作。
>
> 这个回调主要用于保存Activity正在编辑的任何持久状态,以向用户呈现“就地编辑”模型,并确保在启动新Activity之前,如果没有足够的资源启动新Activity而不先销毁当前Activity,则不会丢失任何内容。这也是一个很好的地方停止消耗大量CPU的操作,以便尽快切换到下一个Activity(JavaDoc)。

真正的问题是:每次“用户不再积极地与Activity进行交互,但它仍然在屏幕上可见”时,你是否需要将数据同步到服务器?onPause应该用于保存“UI字段状态”。这取决于你的用例,也许更好的选择是每5分钟同步一次,但我不确定如何在脑海中快速管理关闭服务。

英文:

You could use the java.util.concurrent API if you need an alternative solution. The Executors are quite handy and easy to use.

BTW the onDestroy() javadoc says:
> Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here". I think it could happen that onDestroy is never called.

But also take care in onPause:
> When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure to not do anything lengthy here.
>
> This callback is mostly used for saving any persistent state the activity is editing, to present a "edit in place" model to the user and making sure nothing is lost if there are not enough resources to start the new activity without first killing this one. This is also a good place to stop things that consume a noticeable amount of CPU in order to make the switch to the next activity as fast as possible. (JavaDoc)

The real question is: Do you need to sync data to server EVERY time "the user no longer actively interacts with the activity, but it is still visible on screen"[2]? onPause should be used to save the "UI fields state". It depends on your use case, maybe a better option is to sync every 5 mins, but I am not sure from the top of my head how to manage turning off the service.

huangapple
  • 本文由 发表于 2020年8月21日 06:45:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63514119.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定