简体   繁体   中英

How to detect incoming calls in Android even when the app is terminated

I have a broadcast receiver which detects incoming calls and starts an activity. But it doesnt work sometimes in real devices. How can I make it work all the time?

My receiver:

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

onReceive method

    @Override
    override fun onReceive(context: Context?, intent: Intent) {
        try {
            val state: String? = intent.getStringExtra(TelephonyManager.EXTRA_STATE)
            val incomingNumber: String? =
                intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER)
            if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                Log.d("INFO", incomingNumber.toString())
                Toast.makeText(context, "Gelen Arama $incomingNumber", Toast.LENGTH_SHORT).show()
                if(incomingNumber != null){
                    simpleFloatingWindow = SimpleFloatingWindow(context!!)
                    simpleFloatingWindow.show()
                }
            }
            if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
                //Toast.makeText(context,"Call Received State",Toast.LENGTH_SHORT).show();
            }
            if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                //Toast.makeText(context,"Call Idle State",Toast.LENGTH_SHORT).show();
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

You can't start an activity from the background from Android 10+ devices. Except for the cases:

https://developer.android.com/guide/components/activities/background-starts#exceptions

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