如何在mainactivity中定义广播接收器类和phonestatechange类?

时间:2013-10-24 07:15:19

标签: java android

这是我的手机状态,我正在检查手机状态的变化

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);
}

如何在主要活动中定义此内容?

2 个答案:

答案 0 :(得分: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);

请参阅this

答案 1 :(得分:0)

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

private CustomBroadcastReceiver receiver = new CustomBroadcastReceiver();

然后添加到OnCreate()

registerReceiver(receiver, new IntentFilter(YPUR_ACTION));

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