android - BroadcastReceiver Intent.ACTION_PACKAGE_ADDED/REMOVED Android Oreo

标签 android kotlin broadcastreceiver intentfilter android-broadcast

这是我的广播接收器类及其在 main 中的实现。

问题是 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)
     }
 }

请帮忙。提前致谢。

最佳答案

我可以用下面的代码让它工作

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)
    }
}

关于android - BroadcastReceiver Intent.ACTION_PACKAGE_ADDED/REMOVED Android Oreo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51669361/

相关文章:

java - Android ExpandableListView getChildView 不触发

android 套接字连接,inputStream 在 readline 上与 socket.io 或节点 websocket 服务器卡住

android - 如何将 View 放置在 TextView 的右侧

android - onReceive 异步操作和垃圾回收

Android - 如何使用本地广播接收器?

java - 如何访问 Android 中现有的 .db 文件?

android - mutableStateListOf 反向期间的 ConcurrentModificationException

kotlin - 该循环的功能等效项

android - 错误 : "Type mismatch. Required: Observer<PagedList<MyItem!>!>". 如何修复?

android - 全屏 Intent 不启动 Activity,但在 Android 10 上显示通知