Android检测未接来电

时间:2014-04-24 13:53:21

标签: android broadcastreceiver telephonymanager android-toast

我试图让我的应用程序识别出未接来电。我创建了一个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();
//          }
    }

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

在电话响铃和手机再次闲置之间某处,ringing是否可能被重置为false

1 个答案:

答案 0 :(得分:0)

你不能存储任何"州"广播接收器中的信息。如果你想做一个比较旧的州/新州,我想你可以使用服务。