How to send a WhatsApp message in a BroadcastReceiver when a call ends, even when the app is in a killed state?

85 Views Asked by At

I'm working on an Android application where I need to send a WhatsApp message automatically when a phone call ends. I have a BroadcastReceiver set up to detect the end of a call, and it works perfectly when the app is running in the foreground. However, I'm facing a challenge when the app is in a killed state.

thi is my BroadCast_Reciver class

public class BroadCast_Reciver extends BroadcastReceiver {
Context context;
@Override
public void onReceive(Context context, Intent intent) {
    this.context = context;


    if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
        Toast.makeText(context," Call started...", Toast.LENGTH_SHORT).show();
    }
    else if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_IDLE)){
        Toast.makeText(context," Call end...", Toast.LENGTH_SHORT).show();
        String incomingCallerNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
        openWhatsappContact(incomingCallerNumber);

    }
    else if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)){

        Toast.makeText(context," INcoming Call started...", Toast.LENGTH_SHORT).show();
    }

}


void openWhatsappContact(String number) {
    String message = "Thank you for choosing Kosi Service . We appreciate your trust in us. If you need further assistance, visit our website at KosiService.com.";
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format("https://api.whatsapp.com/send?phone=%s&text=%s", number, message)));
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // Add this flag
    context.startActivity(intent);
}

}

0

There are 0 best solutions below