无法获取TelephonyManager.CALL_STATE_RINGING

时间:2011-05-17 19:51:10

标签: android

我添加了这是我的清单文件 -

        <receiver android:name=".ServiceReceiver">
        <intent-filter>
            <action android:name="android.intent.action.PHONE_STATE" />
        </intent-filter>
    </receiver>
</application>

<uses-permission android:name="android.permission.READ_PHONE_STATE">
</uses-permission>

然后我的服务类是这样的 -

public class ServiceReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    MyPhoneStateListener phoneListener = new MyPhoneStateListener();
    TelephonyManager telephony = (TelephonyManager) context
            .getSystemService(Context.TELEPHONY_SERVICE);
    telephony.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}

}

我的PhoneStateListener是 -

public class MyPhoneStateListener extends PhoneStateListener {

public void onCallStateChanged(int state, String incomingNumber) {
    Log.i("telephony-example", "State changed: " + stateName(state));
}

String stateName(int state) {
    switch (state) {
    case TelephonyManager.CALL_STATE_IDLE:
        Log.d("DEBUG", "***********IDLE********");
        return "Idle";
    case TelephonyManager.CALL_STATE_OFFHOOK:
        Log.d("DEBUG", "***********OFFHOOK********");
        return "Off hook";
    case TelephonyManager.CALL_STATE_RINGING:
        Log.d("DEBUG", "***********RINGING********");
        return "Ringing";
    }
    return Integer.toString(state);
}

}

我能够看到空闲状态。

但是当我打电话给我时,我没有得到振铃状态。为什么呢?

1 个答案:

答案 0 :(得分:14)

我认为你正在混淆两种获取手机状态的方法。如果您使用intent-filter和广播接收器,那么在接收器中无需调用TelephonyManager的listen()。只需检查收到的意图如下:

public void onReceive(Context context, Intent intent) {
    String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
    String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
    if (TelephonyManager.EXTRA_STATE_RINGING.equals(state))
    {
        Log.d("MPR", "Its Ringing [" + number + "]");
    }
    if (TelephonyManager.EXTRA_STATE_IDLE.equals(state))
    {
        Log.d("MPR", "Its Idle");
    }
    if (TelephonyManager.EXTRA_STATE_OFFHOOK.equals(state))
    {
        Log.d("MPR", "Its OffHook");
    }
}