I have a method that detects call state and sends it to DB, but only when activity in foreground. How can i continue method to work when app is in backgound? How and what should i change so it will run when app goes to background?
Here i call method in onCreate() of MainActivity:
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;
}
}
};
This is method:
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);
}
}
});
}