在应用程序的 onStop 中发送 android 中的 http 请求
Sending http request in android in app's onStop
我有一些统计数据需要从我的 Android 4.2+ 应用程序发送到我的服务器并等待响应。事实上,一些用户 运行 它只有一次,所以要从他们那里获取数据,我需要在 main activity.
的 onStop 中发送它
据我所知,请求必须是同步的:如果我在这里创建 http 工作线程 android 将进一步 运行 并在执行 http 请求之前关闭应用程序。
假设只能进行一次发射,我不能指望在下一次发射时检查数据。
我什至考虑过在 onStop 中启动服务(以确保代码将在应用程序停止后执行)来处理这个请求,但它看起来很难看。
你是怎么做到这些的?
我建议使用 IntentService 或 WakeFullIntentService,您可以在 onStop 中触发您的工作。
if I create http working thread here android will just run further and close app before http request performed.
不,android 不会立即终止您的应用程序进程,您可以启动服务,它会完成其工作。实际上系统可能会终止您的应用程序,但您必须立即打开其他繁重的应用程序 - 例如 camera/etc.
为避免您可以通过添加通知使您的服务前台
You can override your onBackPress method and make http request from here by using Async task and in onPostexecute() method call finish() to close activity.
//Something like this
@Override
public void onBackPressed() {
new AsyncTask<Void , Void , Void>(){
@Override
protected Void doInBackground(Void... params) {
//make request
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
// on completion
finish();
}
};
}
我有一些统计数据需要从我的 Android 4.2+ 应用程序发送到我的服务器并等待响应。事实上,一些用户 运行 它只有一次,所以要从他们那里获取数据,我需要在 main activity.
的 onStop 中发送它据我所知,请求必须是同步的:如果我在这里创建 http 工作线程 android 将进一步 运行 并在执行 http 请求之前关闭应用程序。 假设只能进行一次发射,我不能指望在下一次发射时检查数据。 我什至考虑过在 onStop 中启动服务(以确保代码将在应用程序停止后执行)来处理这个请求,但它看起来很难看。
你是怎么做到这些的?
我建议使用 IntentService 或 WakeFullIntentService,您可以在 onStop 中触发您的工作。
if I create http working thread here android will just run further and close app before http request performed.
不,android 不会立即终止您的应用程序进程,您可以启动服务,它会完成其工作。实际上系统可能会终止您的应用程序,但您必须立即打开其他繁重的应用程序 - 例如 camera/etc.
为避免您可以通过添加通知使您的服务前台
You can override your onBackPress method and make http request from here by using Async task and in onPostexecute() method call finish() to close activity.
//Something like this
@Override
public void onBackPressed() {
new AsyncTask<Void , Void , Void>(){
@Override
protected Void doInBackground(Void... params) {
//make request
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
// on completion
finish();
}
};
}