用于在Android中进行调用的BroadcastReceiver不起作用

时间:2017-07-05 15:52:18

标签: java android broadcastreceiver android-broadcastreceiver incoming-call

我正在尝试开发可以记录电话的Android应用程序。所以,在最初的步骤中,我要看看BroadcastReceiver是否会被解雇。 我在AndroidManifest文件中添加了权限,接收者标记。我在OnePlus X上测试。活动开始了,但是当我接到电话时,BroadcastReceiver不会被触发。这里出了什么问题?

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <activity
        android:name="com.example.myapp.MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

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

</application>

</manifest>

PhoneStateReceiver.Java

package com.example.myapp;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.widget.Toast;

public class PhoneStateReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        try {
            System.out.println("Receiver start");
            String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
            String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);

            if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
                Toast.makeText(context,"Incoming Call State",Toast.LENGTH_SHORT).show();
                Toast.makeText(context,"Ringing State Number is -"+incomingNumber,Toast.LENGTH_SHORT).show();


            }
            if ((state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))){
                Toast.makeText(context,"Call Received State",Toast.LENGTH_SHORT).show();
            }
            if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
                Toast.makeText(context,"Call Idle State",Toast.LENGTH_SHORT).show();
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }

    }
}

1 个答案:

答案 0 :(得分:0)

权限READ_PHONE_STATE是一种危险的权限,如果您使用的是marshmallow设备,则必须请求运行时权限,否则您的广播接收器将无法工作,也不会产生错误。

这很可能是您的代码问题的原因,因为您已经在Intent过滤器中正确注册,除了它没有任何错误,因为它只是一个广播接收器并且应该工作,即由Android系统调用。