简体   繁体   中英

How to detect incoming call phone number in Android when app is killed?

I want to detect incoming/outgoing call phone numbers when my app is not running, it is killed. I have implemented the following code by it only detects call if the app is running or in the background but not working when the app is killed.

public class CallReceiver extends BroadcastReceiver {

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

    if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
        String outgoingPhoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
        showToast(context,"Call Outgoing to "+outgoingPhoneNumber);
    }else if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_IDLE)){
        String callEndedNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
        showToast(context,"Call Ended to "+callEndedNumber);
    }else if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)){
        String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
        showToast(context,"Incomming call from "+ incomingNumber);
    }

}

private void  showToast(Context context, String message){

    Toast.makeText(context, message, Toast.LENGTH_SHORT).show();

}

}

Manifests

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

Not exactly an answer, but you can create your custom calling app and then make it default by asking for permission. A demo app can be found here: https://github.com/Abror96/CustomPhoneDialer Look at this app code and you might get it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM