android - Android HTTP Post 请求在后台
问题描述
我有一种方法可以检测调用状态并将其发送到数据库,但仅限于前台活动时。当应用程序处于后台时,我如何继续工作?我应该如何以及应该更改什么以便在应用程序进入后台时运行它?
这里我在 MainActivity 的 onCreate() 中调用方法:
callStateListener = new PhoneStateListener() {
public void onCallStateChanged(final int state, String incomingNumber) {
switch (state){
case TelephonyManager.CALL_STATE_IDLE:
Log.i(TAG, "onCallStateChanged: IDLE = "+state);
if (token!=null) {
updateState(token, String.valueOf(state));
}else {
Log.i(TAG, "onCallStateChanged: ERROR");
}
break;
case TelephonyManager.CALL_STATE_RINGING:
Log.i(TAG, "onCallStateChanged: RING = "+state);
if (token!=null) {
updateState(token, String.valueOf(state));
}
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.i(TAG, "onCallStateChanged: CALL = "+state);
if (token!=null) {
updateState(token, String.valueOf(state));
}
break;
}
}
};
这是方法:
private void updateState(String token, String state) {
Log.i(TAG, "updateState: state"+state);
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("token", token)
.add("state", state)
.build();
Request request = new Request.Builder()
.url("http://update.php")
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d("OkHttp", call.toString());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String responseStr = response.body().string();
Log.d("OkHttp", responseStr);
}
}
});
}
解决方案
推荐阅读
- linux - 在后台 bash 中触发脚本时的依赖性检查
- firebase - Flutter FirebaseAuth:我如何检查用户是否在空白中登录?
- python - 应用 `set()` 在列表中查找最大计数项时的细微差别
- docker - 如何将文件复制到 Minikube Pod
- java - 字母桶 2
- php - PHP Google Oauth API未设置令牌
- r - 如何在ggplot2的geom_hex图中对齐六边形
- vue.js - Vue图像src没有渲染数据返回
- python-3.x - 同情 pprint sin(a_n) 和 s(a_n)
- python - 如何创建每一行的重复值,然后插入一个新的数据框?