How to show incoming call when the app is in background? Android

938 views Asked by At

That's what I trying to do in the background, but nothing happens. I'm using push notifications(Firebase Messaging Service) to run this code.

        phoneAccountHandle = PhoneAccountHandle(
            ComponentName(
                packageName,
                DoctorConnectionService::class.java.name
            ), phoneAccountHandleId
        )
        val builder = PhoneAccount.builder(phoneAccountHandle, "My account")
        builder.setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER or PhoneAccount.CAPABILITY_CONNECTION_MANAGER)
        val phoneAccount = builder.build()
        val test = telecomManager
        telecomManager?.registerPhoneAccount(phoneAccount)
        telecomManager?.addNewIncomingCall(phoneAccountHandle, Bundle())
1

There are 1 answers

0
A.R.B.N On

You can try BroadcastReceiver. Here is my BroadcastReceiver's Class & MainActivity. In here I just Toast a message (Incoming Call) when application is in background:

MainActivity:

public class MainActivity extends AppCompatActivity {
BroadcastReceiver callReceiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    checkPermission();
    callReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          /*Do Whatever You Want When You Reciveing a Call And App is Open*/
        }
    };
    IntentFilter callFilter = new IntentFilter("android.intent.action.PHONE_STATE");
    registerReceiver(callReceiver, callFilter);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(callReceiver);
}

private void checkPermission() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 100);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == 100) {

    }
  }
}

And here is my BroadcastReceiver class:

public class IncomingCallReciver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
    Toast.makeText(context, ".:Incoming Call:.", Toast.LENGTH_SHORT).show();
    /*Do Whatever You Want When You Reciveing a Call And App is In Background*/
  }
}

Then Add READ_PHONE_STATE Permission in Manifest and add BroadcastReceiver's class in Manifest, Inside Application Tag:

<receiver android:name=".IncomingCallReciver">
        <intent-filter>
            <action android:name="android.intent.action.PHONE_STATE" />
        </intent-filter>
</receiver>