Android,处理来电事件

Aas*_*rma 2 android countdowntimer

我正在开发一个具有倒数计时器的应用程序。我只想在电话上有来电时暂停该计时器。有没有办法在我们接到电话时触发事件?

Aks*_*hay 5

我认为你应该扩展PhoneStateListener类。在那个类中你处理电话状态。为此使用清单文件中的权限来处理电话状态(即<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE">)。

并用于TelephonyManager获取手机状态。

 TelephonyManager  manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
 manager.listen(this, LISTEN_CALL_STATE); // Registers a listener object to receive notification of changes in specified telephony states.
Run Code Online (Sandbox Code Playgroud)

并覆盖此方法。

     @Override
public void onCallStateChanged(int state, String incomingNumber) {
    super.onCallStateChanged(state, incomingNumber);
    switch (state) {
    case TelephonyManager.CALL_STATE_OFFHOOK:
    case TelephonyManager.CALL_STATE_RINGING:
        // Here you can perform your task while phone is ringing.
        break;
    case TelephonyManager.CALL_STATE_IDLE:
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)