Android O(reo)广播接收器未触发。

时间:2017-08-22 15:38:56

标签: android broadcastreceiver

我曾经在我的清单中定义了一个接收电话状态的广播接收器,就像这样......

<receiver
            android:name=".TelephonyManagerReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE" />
            </intent-filter>
        </receiver>

我知道在Android O中我需要删除它并在代码中注册接收器,所以我已经完成了这个......

 private BroadcastReceiver callReceiver;

 @Override
     protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

         callReceiver = new BroadcastReceiver() {
             @Override
             public void onReceive(Context context, Intent intent) {

                 Log.i("Phone","received");
             }
         };

         this.registerReceiver(
                 callReceiver,
                 new IntentFilter(TelephonyManager.ACTION_PHONE_STATE_CHANGED)
         ); }

我希望在收到/拨打电话时会看到一些日志记录,但事实并非如此。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

我遇到了同样的问题。我添加了两个动态权限:CALL_PHONE,READ_PHONE_STATE和接收器工作正常,即使它只在Manifest文件中声明。 我在模拟器和手机上测试了解决方案 - Nexus 5.

(这种方式在应用程序打开或在后台运行时,如果你关闭应用程序它将无法正常工作。为此,我认为你必须使用前台服务)

我希望现在还为时不晚。

答案 1 :(得分:0)

您是否在清单中添加了权限并在运行时请求权限?

清单:

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

运行时:

private static final int REQUEST_PHONE_STATE = 1;
private static String[] PERMISSIONS_PHONE_STATE = {
            Manifest.permission.READ_PHONE_STATE
};

public static void verifyPhonePermissions(Activity activity) {
    // Check if we have this permission
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_PHONE_STATE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_PHONE_STATE,
                REQUEST_PHONE_STATE
        );
    }
}