When there are outgoing and incoming calls, toast should appear on the screen but it does not appear. Is the code incorrect?
Manifast premissions:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
Manifast (receiver):
<receiver android:name=".model.CallReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
MainActivity
if (ContextCompat.checkSelfPermission( this, READ_PHONE_STATE)!=PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions( this, new String[]{READ_PHONE_STATE} , 369);
}
class:
public class CallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context , Intent intent) {
if (intent.getStringExtra( TelephonyManager.EXTRA_STATE )==TelephonyManager.EXTRA_STATE_OFFHOOK){
showToastMsg(context,"phone call is Started...");
}else { if (intent.getStringExtra( TelephonyManager.EXTRA_STATE )==TelephonyManager.EXTRA_STATE_IDLE){
showToastMsg(context,"phone call is Ended...");
}else { if (intent.getStringExtra( TelephonyManager.EXTRA_STATE )==TelephonyManager.EXTRA_STATE_RINGING){
showToastMsg(context,"Incoming Call...");
}
}
}
}
private void showToastMsg(Context c,String msg) {
Toast.makeText( c, msg, Toast.LENGTH_LONG).show();
}
}
2
Answers
You need the service to handle incoming or outgoing calls when the app is closed.
Manifest.xml
CallReceiver
CallService
Use this code it is working on android 11 and 9
in manifest
Call Receiver