即使应用程序处于终止状态,如何在通话结束时在 BroadcastReceiver 中发送 WhatsApp 消息?

问题描述 投票:0回答:1

我正在开发一个 Android 应用程序,我需要在电话结束时自动发送 WhatsApp 消息。我设置了一个 BroadcastReceiver 来检测通话结束,当应用程序在前台运行时它可以完美工作。然而,当应用程序处于终止状态时,我面临着挑战。

这是我的 BroadCast_Reciver 类

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);
}

}

broadcastreceiver whatsapp phone-call background-service
1个回答
0
投票

要在电话结束时自动发送 WhatsApp 消息,您可以使用 BroadcastReceiver。这是 BroadcastReceiver 类的修改版本:

确保您在 AndroidManifest.xml 中拥有必要的权限。 修改您的 BroadcastReceiver 以处理通话状态更改并在通话结束时打开 WhatsApp。 创建一个在后台运行的服务,在该服务中注册您的 BroadcastReceiver,并在 AndroidManifest.xml 中声明该服务。 在 BOOT_COMPLETED 上启动服务,以确保即使您的应用程序被终止它也能正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.