gpt4 book ai didi

java - 无法使用 BroadcastReceiver [Marshmallow] 检测来电号码

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:20:26 24 4
gpt4 key购买 nike

每当我使用 BroadcastReceiver 接到来电时,我都会尝试记录电话号码。但是,当我调用我的号码时,我没有收到任何log。这是代码:

AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.abc.broadcast_phone" >

<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" >

<receiver android:name=".MyPhoneReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" >
</action>
</intent-filter>
</receiver>
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

MainActivity.java

    public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent("tuet");
sendBroadcast(intent);
}
}

MyPhoneReceiver.java

    public class MyPhoneReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null)
{
String state = extras.getString(TelephonyManager.EXTRA_STATE);

if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
String phoneNumber = extras
.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.e("DEBUG", phoneNumber);
}
}
}
}

我正在使用 SDK 23 进行编译并且目标也是 Marshmallow,在这种情况下我应该使用运行时权限吗?或者我错过了什么?

EDIT-1

似乎问题只与 Marshmallow 相关,当我降级目标 sdk 版本时,这工作正常:targetSdkVersion 22

那么,如何调整它以在 SDK23+ 及更高版本中工作?

最佳答案

根据 onCallStateChanged() documentation :

incoming call phone number. If application does not have READ_PHONE_STATE permission, an empty string will be passed as an argument.

READ_PHONE_STATEdangerous permission那一定是 requested at runtime当您根据 Marshmallow Behavior Changes 以 API 23 或更高版本为目标时

关于java - 无法使用 BroadcastReceiver [Marshmallow] 检测来电号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38864621/

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