Part 1: when app opens my MainActivity() gets all call logs and saves in DB Part 2: When app is closed and user makes multiple calls and recieves multiple calls, how do i update them in db.
possible solutions: solution 1: every time when app opens delete all call log and save all call logs in app again.
solution 2: using broadcast reciever, when call is ended enter save record in db, i.e every call will be recorded once its finished when i used solution 2 it worked but when app is closed it does not save any data. it only works when app is running in background.
is there any other way to save them?? any efficient ways?
here is the code for listining to call end
@Override
public void onReceive(Context context, Intent intent) {
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); //TelephonyManager object
//check if listener has already been instantiated
if(phoneStateListener == null) {
phoneStateListener = new MyPhoneStateListener();
telephony.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
Bundle bundle = intent.getExtras();
String phoneNr = bundle.getString("incoming_number");
Log.v("checker", "phoneNr: " + phoneNr);
mContext = context;
}
}
/* Custom PhoneStateListener */
private class MyPhoneStateListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if (incomingNumber != null && incomingNumber.length() > 0)
incoming_number = incomingNumber;
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
Log.d("checker", "CALL_STATE_RINGING");
prev_state = state;
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.d("checker", "CALL_STATE_OFFHOOK");
prev_state = state;
break;
case TelephonyManager.CALL_STATE_IDLE:
List<CallModelTable> callLogDetails;
new Handler().postDelayed(PhoneStateBroadcastReceiver.this::saveLastCallLogInDb, 200);
Log.d("checker", "CALL_STATE_IDLE==>" + incoming_number);
if ((prev_state == TelephonyManager.CALL_STATE_OFFHOOK)) {
prev_state = state;
//Answered Call which is ended
Log.d("checker", "answered ended==>");
}
if ((prev_state == TelephonyManager.CALL_STATE_RINGING)) {
prev_state = state;
//Rejected or Missed call
Log.d("checker", "rejected or missed: ");
}
break;
}
}
}
There are two ways to get phone-state events: listening for
android.intent.action.PHONE_STATEbroadcasts and using aPhoneStateListener.The second approach will only work when the app is alive, and the listener will get destroyed shortly after the app moves to the background.
For the first approach, you just need to register a broadcast receiver in your manifest like so:
And then handle the events in the BroadcastReceiver class, no need to register any added listener.
Check out the tutorial here: https://medium.com/@saishaddai/how-to-know-when-a-device-is-ringing-in-android-57e516d0ab42