Android中的广播接收器不起作用

Posted

技术标签:

【中文标题】Android中的广播接收器不起作用【英文标题】:Broadcast receiver in Android does not work 【发布时间】:2020-09-14 21:30:05 【问题描述】:

我有一个运行包安装程序会话的简单服务,我想从中获取状态。包管理器有不同的状态,根据我收到的状态,我希望我的活动创建一个对话框,但我遇到了问题。 InstallerService.kt:

class InstallerService: Service() 

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int 
        when (intent.getIntExtra(PackageInstaller.EXTRA_STATUS, -999)) 
            PackageInstaller.STATUS_PENDING_USER_ACTION -> 
                Toast.makeText(this, "Installing...", Toast.LENGTH_SHORT).show()
                Log.d(TAG, "Requesting user confirmation for installation")
                val confirmationIntent =
                    intent.getParcelableExtra<Intent>(Intent.EXTRA_INTENT)
                confirmationIntent?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                try 
                    startActivity(confirmationIntent)
                 catch (e: Exception) 
                
            
            PackageInstaller.STATUS_SUCCESS -> 
                Log.d(TAG, "Installation succeed")
                getSharedPreferences("installPrefs", Context.MODE_PRIVATE).edit().putBoolean("isInstalling", false).apply()
                val mIntent = Intent(MainActivity.INSTALL_COMPLETED)
                mIntent.action = MainActivity.INSTALL_COMPLETED
                LocalBroadcastManager.getInstance(this).sendBroadcast(mIntent)
            
            PackageInstaller.STATUS_FAILURE_ABORTED -> 
                val mIntent = Intent(MainActivity.INSTALL_ABORTED)
                mIntent.action = MainActivity.INSTALL_ABORTED
                LocalBroadcastManager.getInstance(this).sendBroadcast(mIntent)
            
            PackageInstaller.STATUS_FAILURE_INVALID -> 
                val mIntent = Intent(MainActivity.INSTALL_INVALID)
                mIntent.action = MainActivity.INSTALL_INVALID
                LocalBroadcastManager.getInstance(this).sendBroadcast(mIntent)
            
            PackageInstaller.STATUS_FAILURE_CONFLICT -> 
                val mIntent = Intent(MainActivity.INSTALL_CONFLICT)
                mIntent.action = MainActivity.INSTALL_CONFLICT
                LocalBroadcastManager.getInstance(this).sendBroadcast(mIntent)
            
            PackageInstaller.STATUS_FAILURE_STORAGE -> 
                val mIntent = Intent(MainActivity.INSTALL_STORAGE)
                mIntent.action = MainActivity.INSTALL_STORAGE
                LocalBroadcastManager.getInstance(this).sendBroadcast(mIntent)
            
            PackageInstaller.STATUS_FAILURE_BLOCKED -> 
                val mIntent = Intent(MainActivity.INSTALL_BLOCKED)
                mIntent.action = MainActivity.INSTALL_BLOCKED
                sendBroadcast(mIntent)
            
            else -> 
                Log.d(TAG, "Installation failed")
                val mIntent = Intent(MainActivity.INSTALL_FAILED)
                mIntent.action = MainActivity.INSTALL_ABORTED
                sendBroadcast(mIntent)
            
        
        stopSelf()
        return START_NOT_STICKY
    

    @Nullable
    override fun onBind(intent: Intent?): IBinder? 
        return null
    

    companion object
        const val TAG = "VMInstall"
    


现在当 k 尝试接收意图动作时,它根本不做任何事情 MainActivity.kt:

class MainActivity : Main() 

    private var isParent = true

    override fun onCreate(savedInstanceState: Bundle?) 

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val toolbar: Toolbar = findViewById(R.id.home_toolbar)
        setSupportActionBar(toolbar)

        val navHost = findNavController(R.id.bottom_nav_host)
        val appBarConfiguration = AppBarConfiguration(navHost.graph)
        toolbar.setupWithNavController(navHost, appBarConfiguration)

        navHost.addOnDestinationChangedListener_, currFrag: NavDestination, _ ->
            isParent = when (currFrag.id) 
                R.id.home_fragment -> true
                else -> false
            

            setDisplayHomeAsUpEnabled(!isParent)

        

        registerReceivers()

    

    private val broadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() 
        override fun onReceive(context: Context, intent: Intent) 
            when (intent.action) 
                INSTALL_COMPLETED -> launchVanced()
            
        
    

    override fun onDestroy() 
        super.onDestroy()
        LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver)
    

    override fun onPause() 
        super.onPause()
        LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver)
    

    override fun onResume() 
        super.onResume()
        registerReceivers()
    

    private fun registerReceivers() 
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, IntentFilter(
            INSTALL_COMPLETED
        ))
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, IntentFilter(
            INSTALL_ABORTED
        ))
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, IntentFilter(
            INSTALL_BLOCKED
        ))
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, IntentFilter(
            INSTALL_STORAGE
        ))
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, IntentFilter(
            INSTALL_CONFLICT
        ))
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, IntentFilter(
            INSTALL_FAILED
        ))
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, IntentFilter(
            INSTALL_INVALID
        ))

    

    companion object 
        const val INSTALL_COMPLETED = "Installation completed"
        const val INSTALL_ABORTED = "user aborted installation"
        const val INSTALL_BLOCKED = "user blocked installation"
        const val INSTALL_STORAGE = "there was an error with storage.\n Hold up how is that even possible?"
        const val INSTALL_CONFLICT = "app conflicts with already installed app"
        const val INSTALL_FAILED = "it just failed idk"
        const val INSTALL_INVALID = "apk files are invalid"

    

有什么建议吗?提前致谢

【问题讨论】:

您的Service 运行了吗?广播Intent 发送成功了吗? logcat 中是否显示任何错误?你的BroadcastReceiveronReceive() 有被调用吗?请添加调试日志和/或设置断点以缩小问题范围。 对不起,忘记将问题标记为已解决。我实际上是通过使用 intent.action.equals(INSTALL_COMPLETED) 而不是当前实现来修复它 【参考方案1】:

通过使用修复

private val broadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() 
    override fun onReceive(context: Context, intent: Intent) 
        when 
            inten.action.equals(INSTALL_COMPLETED) -> launchVanced()
        
    

代替

private val broadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() 
    override fun onReceive(context: Context, intent: Intent) 
        when (intent.action) 
            INSTALL_COMPLETED -> launchVanced()
        
    

【讨论】:

这毫无意义。这两个代码块在功能上是等效的。如果它与一个一起工作,它应该与另一个一起工作。请解释一下。 我不知道它是如何工作的以及为什么,但它确实有效。我没有改变其他任何东西

以上是关于Android中的广播接收器不起作用的主要内容,如果未能解决你的问题,请参考以下文章

应用程序未运行时广播接收器不起作用

当手机处于睡眠模式时,为什么用于来电的广播接收器在棒棒糖上不起作用

带有活动的广播接收器服务反馈不起作用

Toast 和广播接收器不起作用

应用程序关闭时,带有广播接收器的工作管理器不起作用

Android 第六讲 广播接收器和服务