0

我试图让我的应用程序识别何时有未接来电。我创建了一个 BroadcastReceiver 来检测手机状态何时发生变化。这是我的onReceive()方法:

public void onReceive(Context context, Intent intent) {
    boolean ringing = false, callReceived = false;
    String callerPhoneNumber = "";
    String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);

    if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) {
        ringing = true;
        Bundle bundle = intent.getExtras();
        callerPhoneNumber= bundle.getString("incoming_number");

        if (ringing) {
            Toast.makeText(context, "Phone call from: " + callerPhoneNumber, Toast.LENGTH_LONG).show();
        }
    }

    if (TelephonyManager.EXTRA_STATE_OFFHOOK.equals(state)) {
        callReceived = true;
        Toast.makeText(context, "Call received.", Toast.LENGTH_LONG).show();
    }

    if (TelephonyManager.EXTRA_STATE_IDLE.equals(state)) {
//          Toast.makeText(context, "Phone is idle", Toast.LENGTH_LONG).show();

        if (ringing) {
            Toast.makeText(context, "ringing is true", Toast.LENGTH_LONG).show();
        }

//          if (ringing && !callReceived) {
//              Toast.makeText(context, "It was A MISSED CALL from : " + callerPhoneNumber, Toast.LENGTH_LONG).show();
//          }
    }

我遇到的问题是应用程序检测到手机何时响铃、设置ringingtrue并显示适当的 toast 消息。但是,当手机的状态为 时idle,它不会进入显示toast 消息的if (ringing)语句。ringing is true但是,如果我在它上面的 toast 消息中发表评论,它将正确打印Phone is idle.

是否有可能ringing被重置到false电话响铃和电话再次空闲之间的某个地方?

4

1 回答 1

0

您不能在广播接收器中存储任何“状态”信息。如果您想比较旧状态/新状态,我认为您可以使用服务。

于 2014-04-24T13:55:53.160 回答