android - 从后台刷应用程序并想调用 api
问题描述
我创建了一个 DeviceShutDownReceiver 接收器。
public class DeviceShutDownReceiver extends BroadcastReceiver {
Context mContext;
@Override
public void onReceive(Context context, Intent intent)
{
mContext = context;
//Make user offline when device is getting Shut down.
new MakeUserOffline().execute();
}
private class MakeUserOffline extends AsyncTask<Void, Void, String> {
// ProgressDialog dialog = new ProgressDialog(Reg);
//dialog.
String result;
@Override
protected String doInBackground(Void... params) {
Log.i("Check", "1()");
String strUserId = BaseActivity.getUserId();
int userId = Integer.parseInt(strUserId);
final UserAvailabilityStatus obj = new UserAvailabilityStatus(userId,false);
String webAddressToPost = Constants.BASE_URL + "DriverLocation/UpdateDriverOnlineStatus";
try {
Log.i("Check", "2()");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(webAddressToPost);
Gson gson = new GsonBuilder().create();
String jsonStr = gson.toJson(obj);
httpPost.addHeader("User-Agent", "Custom-Agent 1.0");
httpPost.addHeader(Constants.AUTH_HEADER_KEY,Constants.AUTH_HEADER_VALUE);
StringEntity se = new StringEntity(jsonStr);
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json;charset=UTF-8"));
httpPost.setEntity(se);
HttpResponse response = httpClient.execute(httpPost);
Log.i("Check", "3()");
if (response.getStatusLine().getStatusCode() == 200) {
// Get the response string
InputStream inputStream = null;
inputStream = response.getEntity().getContent();
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Failure";
UserAvailabilityStatus responseId = gson.fromJson(
result, UserAvailabilityStatus.class);
// int responseId = fooFromJson.Id;
Log.i("Check", result);
if ((null == responseId)) {
// Log.w(TAG, String.format("onLoadFinished() : But null value returned!"));
//Toast.makeText(mContext, "Status not updated", Toast.LENGTH_LONG).show();
}
else {
Log.i("Check", result);
if(responseId.getResult().equalsIgnoreCase("Success.")) {
//Toast.makeText(mContext, "Status updated successfully", Toast.LENGTH_SHORT).show();
saveAvailableStatusSharedPref(false);
Log.i("Check", responseId.getResult());
}
else{
//Toast.makeText(mContext, "Status could not be updated", Toast.LENGTH_SHORT).show();
}
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
}
return null;
}
@Override
protected void onPreExecute(){
super.onPreExecute();
// dialog.setMessage("Loading...");
// dialog.show();
}
@Override
protected void onPostExecute(String result) {
}
}
private void saveAvailableStatusSharedPref(Boolean isAvailable){
SharedPreferences sharedpreferences = mContext.getSharedPreferences(
Constants.PREF_USER_AVAILABLE_STATUS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(Constants.PREF_USER_AVAILABLE_STATUS, isAvailable);
editor.commit();
}
private static String convertInputStreamToString(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
我从清单文件中调用这个接收器。
<receiver android:name=".DeviceShutDownReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_SHUTDOWN" />
</intent-filter>
</receiver>
当我从任务管理器刷应用程序时,我想调用一个 api,但是这个 api 没有调用。我想这个接收器没有打电话。
如果我遗漏了什么,请提出建议。
#######################################3解决方案
如果我理解正确,您想webrequest
在应用程序被终止时而不是在设备关闭时进行。
因此,您必须查看 Android Activity Lifecycle
来源:https ://developer.android.com/guide/components/activities/activity-lifecycle
将您的代码放在onStop
oronDestroy
中。无需自定义广播接收器。
推荐阅读
- vba - 我想在事件过程中设置一个新记录表单字段的值
- flutter - 如何修复“无法快照构建脚本”
- visual-studio - 如何使用 Visual Studio 2019 为解决方案中的多个项目指定自定义代码分析规则集?
- apache - LAN连接到wamp主页,而不是www中的项目
- asp.net-mvc - WebActivatorEx 启动方法未运行
- apostrophe-cms - 在 ApostropheCMS 中将 JS 从 npm 模块推送到浏览器
- python - Google Bigquery 存储:读取 to_dataframe 时出现 DeadlineExceeded 错误
- spring - 未对 @Transactional 注解执行回滚
- python-3.x - 是否可以在不定义顺序或关键字之间的单词数的情况下使用基于空间规则的匹配?
- node.js - 断言传递给存根函数的函数是正确的函数