【问题标题】:BroadcastReceiver Intent.ACTION_PACKAGE_ADDED/REMOVED Android OreoBroadcastReceiver Intent.ACTION_PACKAGE_ADDED/REMOVED Android Oreo
【发布时间】:2019-01-11 03:42:29
【问题描述】:

这是我的广播接收器类及其在 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)
     }
 }

请帮忙。提前致谢。

【问题讨论】:

    标签: android kotlin broadcastreceiver intentfilter android-broadcast


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      通常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>
      

      编辑:请参阅此post,其中建议使用 ACTION_PACKAGE_FULLY_REMOVED 或JobScheduler

      也尝试在模拟器上重新安装应用程序

      【讨论】:

      • 我试图在清单上声明我的广播接收器,但没有运气。所以我尝试了编程方式,正如您从我发布的代码中看到的那样,但仍然无法正常工作
      • 它看起来有人遇到了你的问题并修复了将数据包添加到清单中,现在你可能针对 oreo/26 你不能使用清单所以应该看看是否可以在你的IntentFilter stackoverflow.com/questions/11246326/…
      • 不知道有没有办法以编程方式添加数据包
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-24
      • 1970-01-01
      • 1970-01-01
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多