我正在尝试创建静态广播接收器,但无法正常工作。
我正在使用API级别25。
Android list
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.broadcastreceivertry">
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<receiver
android:name=".ScreenReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.SCREEN_ON"/>
<action android:name="android.intent.action.SCREEN_OFF"/>
</intent-filter>
</receiver>
</application>
</manifest>
ScreenReceiver.java
package com.example.broadcastreceivertry;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class ScreenReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.v("Screen Update", "Screen ON/OFF");
}
}
MainActivity.kt
package com.example.broadcastreceivertry
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.telephony.SmsManager
import android.widget.Button
class MainActivity : AppCompatActivity() {
var SCREEN_INTENT = "Screen.Intent"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
代码运行后,无法接收android系统发出的广播。
如果我在MainActivity中动态注册这些接收器,那么就没有问题。但是在这个静态注册的接收器中,我无法广播。
最佳答案
Note: If your app targets API level 26 or higher, you cannot use the manifest to declare a receiver for implicit broadcasts (broadcasts that do not target your app specifically), except for a few implicit broadcasts that are exempted from that restriction. In most cases, you can use scheduled jobs instead.
这意味着,如果您确实需要广播接收器,则应通过代码动态注册和注销它
如@MD所述,this URL阐明了为什么不允许使用该URL,以及如何处理此问题。
Android 7.0
Android 7.0(API级别24)及更高版本不会发送以下系统广播:
ACTION_NEW_PICTURE
ACTION_NEW_VIDEO
另外,定位到Android 7.0及更高版本的应用必须使用以下命令注册
CONNECTIVITY_ACTION
广播registerReceiver(BroadcastReceiver, IntentFilter)
。在 list 中声明接收者无效。
Official site将描述广播接收方的所有变化
关于android - 静态BroadcastReceiver无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56946054/