我想听一个来电。

我知道您必须在AndroidManifest内部授予权限,并设置接收方为

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




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


但是,在我的项目中,我通过代码设置了接收方,

IntentFilter filter = new IntentFilter();
filter.addAction( ... );
registerReceiver(broadcastReceiver, filter);


我在addAction放在哪里
我用创建了BroadcastReceiver

private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) { ...


然后,在其中,我使用TelephonyManager.ACTION_PHONE_STATE_CHANGED从意图中采取操作,然后检查它是哪个操作。
它非常适合蓝牙

filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);




switch (action) {
    case BluetoothAdapter.ACTION_DISCOVERY_STARTED: ...


但是它不会检查String action = intent.getAction();

因此,我的问题是:
如何设置操作(TelephonyManager.ACTION_PHONE_STATE_CHANGED)来侦听状态变化?
addAction()不正确吗?
如果我放弃并在AndroiManifest中设置接收器,如何设置蓝牙过滤器?我在用着

BluetoothDevice.ACTION_FOUND
BluetoothAdapter.ACTION_DISCOVERY_STARTED
BluetoothAdapter.ACTION_DISCOVERY_FINISHED

最佳答案

首先注册您的活动的接收者

this.registerReceiver(this.broadcastReceiver, new IntentFilter(TelephonyManager.ACTION_PHONE_STATE_CHANGED));

这是broadcastReceiver:
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);

        if (state == null) {

            //Outgoing call
            String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
            Log.e("tag", "Outgoing number : " + number);

        } else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {

            Log.e("tag", "EXTRA_STATE_OFFHOOK");

        } else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {

            Log.e("tag", "EXTRA_STATE_IDLE");

        } else if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {

            //Incoming call
            String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
            Log.e("tag", "Incoming number : " + number);

        } else
            Log.e("tag", "none");
    }
};

09-26 11:31