检查通话中断 - Android Lollipop

Check for call interruption - Android Lollipop

我在 onPause 中使用以下代码来检查我的应用中的通话中断

//called inside ONPAUSE i.e. whenever my app is interrupted
ActivityManager activityManager = (ActivityManager)getBaseContext().getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> runningTasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
String packageLaunched = runningTasks.get(0).baseActivity.getPackageName();

// see package name of app which interrupted my app 
if (!packageLaunched.contains("package.name.of.my.app")) {
    // do whatever when any other app interrups, as its on top.
}

问题是,
packageLaunched 用于在 android.
的早期版本上调用中断我的应用程序时更改 但是在 android 上,Lollipop 调用不在任何 运行 任务中:/

如何跟踪来自我的 android 应用程序的来电?

为来电意图注册 BroadCastReciever 并在 onRecieveIntent 中执行。虽然只是一个解决方法,但在所有情况下和所有 os 版本都可以解决问题。

此解决方案适用于 android 的每个版本,包括 lollipop
使用此广播接收器

class TeleListener extends PhoneStateListener {
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);
            switch (state) {
            case TelephonyManager.CALL_STATE_IDLE:
                // CALL_STATE_IDLE;
                Toast.makeText(getApplicationContext(), "CALL_STATE_IDLE",
                        Toast.LENGTH_LONG).show();
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
                // CALL_STATE_OFFHOOK;
                Toast.makeText(getApplicationContext(), "CALL_STATE_OFFHOOK",
                        Toast.LENGTH_LONG).show();
                break;
            case TelephonyManager.CALL_STATE_RINGING:
                // CALL_STATE_RINGING
                Toast.makeText(getApplicationContext(), incomingNumber,
                        Toast.LENGTH_LONG).show();
                Toast.makeText(getApplicationContext(), "CALL_STATE_RINGING",
                        Toast.LENGTH_LONG).show();
                break;
            default:
                break;
            }
        }
    }  

然后在onCreate中这样注册

TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        TelephonyMgr.listen(new TeleListener(), PhoneStateListener.LISTEN_CALL_STATE);  

是的,请不要错过

干杯!您的问题已解决 ;)