BroadcastReceiver Intent.ACTION\u软件包\u添加/删除Android Oreo

BroadcastReceiver Intent.ACTION\u软件包\u添加/删除Android Oreo,android,kotlin,broadcastreceiver,intentfilter,android-broadcast,Android,Kotlin,Broadcastreceiver,Intentfilter,Android Broadcast,这是我的广播接收机类及其主要实现 问题是,onReceive方法从未被调用 class MyBroadcastReceiver : BroadcastReceiver() { override fun onReceive(p0: Context?, p1: Intent?) { Toast.makeText(p0, "It works", Toast.LENGTH_LONG).show() } } class MainActivity : AppCompatActivity(

这是我的广播接收机类及其主要实现

问题是,
onReceive
方法从未被调用

class MyBroadcastReceiver : BroadcastReceiver() {
  override fun onReceive(p0: Context?, p1: Intent?) {
     Toast.makeText(p0, "It works", Toast.LENGTH_LONG).show()
  }
}

class MainActivity : AppCompatActivity() {
     ......

     private var broadcastReceiver: MyBroadcastReceiver = MyBroadcastReceiver()

     override fun onCreate(savedInstanceState: Bundle?) {
            ......

            registerReceiver(broadcastReceiver, IntentFilter().apply {
                addAction(Intent.ACTION_PACKAGE_ADDED)
                addAction(Intent.ACTION_PACKAGE_REMOVED)
            })
     }

     override fun onDestroy() {
            super.onDestroy()
            unregisterReceiver(broadcastReceiver)
     }
 }

请帮忙。提前感谢。

通常,
广播接收器
需要设置多个步骤

首先,你有没有把清单交给接收者

<receiver android:name=".MyBroadcastReceiver"  android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
        <action android:name="android.intent.action.INPUT_METHOD_CHANGED" />
    </intent-filter>
</receiver>

,建议的操作包在哪里被完全删除或作业调度程序


同时尝试在emulator上重新安装应用程序

我可以使用以下代码使其正常工作

class KotlinBroadcastReceiver(action: (context: Context, intent: Intent) -> Unit) : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) = action(context, intent)
}

class MainActivity : AppCompatActivity() {
    private val broadcastReceiver = KotlinBroadcastReceiver { context, _ ->
        Toast.makeText(context, "It works", Toast.LENGTH_LONG).show()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        registerReceiver(broadcastReceiver, IntentFilter().apply {
            addAction(Intent.ACTION_PACKAGE_ADDED)
            addAction(Intent.ACTION_PACKAGE_REMOVED)
            addDataScheme("package") // I could not find a constant for that :(
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(broadcastReceiver)
    }
}

我试图在舱单上申报我的广播接收器,但运气不好。因此,我尝试了编程,正如您从我发布的代码中看到的,但仍然无法工作。看起来有人遇到了您的问题,并修复了将数据包添加到清单中的问题,现在,由于您可能以oreo/26为目标,您无法使用清单,因此应该看看是否可以在您的IntentFilter中插入此命令。我不知道是否有方法以编程方式添加数据包