Search code examples
androidbroadcastreceiver

Android BroadcastReceiver Not Working When App Killed


I'm trying to do an app that gets the caller number, send it to my web api, get the response and show it response as pop up on the screen which includes additional information about call. This won't be a public app. When I'm testing on emulator it works in all cases as expected. I installed app on my mobile phone and tested it as I do on emulator and worked as expected. When i press "Recent Apps" button and swipe it out, it suddenly stops receiving call and display popup. I have proper AndroidManifest entries.

AndroidManifest.xml

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.INTERNET" />

//other parts of manifest file


<receiver
        android:name=".CallReceiver"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.PHONE_STATE" />
        </intent-filter>
    </receiver>

BroadcastReceiver Class

public class PhonecallReceiver extends BroadcastReceiver  {

//some declarations

@Override
public void onReceive(Context context, Intent intent) {

    Date currentTime = Calendar.getInstance().getTime();
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference("OnReceive");
    myRef.setValue("PhonecallReceiver onReceive.");
    //other codes

I added Firebase to see whats going on when a call comes. On emulator it puts an entry to Firebase in all cases(App swiped out, screen locked etc.) but when on my phone it only adds record to Firebase when app is active in Recent apps.

I need to receive incoming call data even when app is swiped out from recent apps.

Phone: Xiaomi Redmi Note 4 on Android 7.0 with latest available updates applied.


Solution

  • Fixed the problem with another approach. Instead registering BroadcastReceiver in the AndroidManifest file, created a Foreground service and programmatically created BroadcastReceiver there. Also when Activity get destroyed it may kill the service as well. I added restart service code at onTaskRemoved method to restart service when it gets killed along with app. Now it works in all cases. As downside, it has to show ongoing notification unless user blocks it which is not a problem in my case.