0

这是我的 phonestate 类,我在其中检查手机状态变化

public class CustomPhoneStateListener extends PhoneStateListener {

private static final String TAG = "CustomPhoneStateListener";

public void onCallStateChange(int state, String incomingNumber){

        Log.v(TAG, "WE ARE INSIDE!!!!!!!!!!!");
        Log.v(TAG, incomingNumber);

        switch(state){
                case TelephonyManager.CALL_STATE_RINGING:
                        Log.d(TAG, "RINGING");
                        break;
        }        }

这是我与广播连接的广播接收器类

    public class CustomBroadcastReceiver extends BroadcastReceiver {

private static final String TAG = "CustomBroadcastReceiver";

@Override
public void onReceive(Context context, Intent intent) {
        Log.v(TAG, "WE ARE INSIDE!!!!!!!!!!!");
    TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        CustomPhoneStateListener customPhoneListener = new CustomPhoneStateListener();

    telephony.listen(customPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);


    Bundle bundle = intent.getExtras();
    String phoneNr= bundle.getString("incoming_number");
        Log.v(TAG, "phoneNr: "+phoneNr);
}

如何在主要活动中定义这个?

4

2 回答 2

0

将此包含在您的 android 清单中

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

如果您想在活动中收听电话状态,请使用它而不是 BroadcastReceiver 类。将此包含在您的活动中:

TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
PhoneStateListener listener = new PhoneStateListener() {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            String stateString = "N/A";
            switch (state) {
            case TelephonyManager.CALL_STATE_IDLE:
                stateString = "Idle";
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
                stateString = "Off Hook";
                break;
            case TelephonyManager.CALL_STATE_RINGING:
                stateString = "Ringing";
                break;
            }
        }
    };

    // Register the listener with the telephony manager
    telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);

看到这个

于 2013-10-24T07:29:48.497 回答
0

只需将其放入您的活动中,例如:

private CustomBroadcastReceiver receiver = new CustomBroadcastReceiver();

然后添加到 OnCreate()

registerReceiver(receiver, new IntentFilter(YPUR_ACTION));

但是将 TelephonyManager 放在 BroadcastReceiver 中是没有意义的。您可以像上面的答案一样将其添加到您的活动中。

于 2013-10-24T07:34:36.117 回答