gpt4 book ai didi

java - Android 中来电的 BroadcastReceiver 不起作用

转载 作者:行者123 更新时间:2023-11-29 02:39:56 24 4
gpt4 key购买 nike

我正在尝试开发可以录音的安卓应用程序。因此,在第一步中,我必须查看 BroadcastReceiver 是否被解雇。我在 AndroidManifest 文件中添加了权限、接收者标签。我正在 OnePlus X 上进行测试。Activity 已启动,但当我接到电话时 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();
}

}
}

最佳答案

权限READ_PHONE_STATE是一个危险的权限,如果你在棉花糖设备上,你必须请求运行时权限,否则你的广播接收器将无法工作,也不会抛出错误。

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

关于java - Android 中来电的 BroadcastReceiver 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44930900/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com