Kotlin中的BroadcastReceiver不起作用

时间:2018-01-29 05:25:55

标签: android kotlin broadcastreceiver android-broadcastreceiver

使用本手册http://www.techotopia.com/index.php/Kotlin_Android_Broadcast_Intents_and_Broadcast_Receivers#.EF.BB.BFSummary我已经在Kotlin中实现了BroadcastReceiver,所以我希望在重新启动应用程序后会启动但不会。

请帮忙。谢谢!

广播接收器

class BroadcastReceiverOnBootComplete  : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action.equals(Intent.ACTION_BOOT_COMPLETED, ignoreCase = true)) {
            val message = "Broadcast intent detected " + intent.action
            Toast.makeText(context, message, Toast.LENGTH_LONG).show()
        }
    }
}

清单文件

<?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.simplemobiletools.applauncher"
    android:installLocation="internalOnly">

    <uses-permission
        android:name="android.permission.USE_FINGERPRINT"
        tools:node="remove"/>

    <permission
        android:name="com.simplemobiletools.applauncher.permission.INSTALL_SHORTCUT"
        android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
        android:protectionLevel="dangerous"
        android:label="@string/permlab_install_shortcut"
        android:description="@string/permdesc_install_shortcut" />
    <permission
        android:name="com.simplemobiletools.applauncher.permission.READ_SETTINGS"
        android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
        android:protectionLevel="normal"
        android:label="@string/permlab_read_settings"
        android:description="@string/permdesc_read_settings"/>
    <permission
        android:name="com.simplemobiletools.applauncher.permission.WRITE_SETTINGS"
        android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
        android:protectionLevel="signatureOrSystem"
        android:label="@string/permlab_write_settings"
        android:description="@string/permdesc_write_settings"/>
    <permission
        android:name="com.simplemobiletools.applauncher.permission.RECEIVE_LAUNCH_BROADCASTS"
        android:protectionLevel="signature"
        />
    <permission
        android:name="com.simplemobiletools.applauncher.permission.RECEIVE_FIRST_LOAD_BROADCAST"
        android:protectionLevel="signatureOrSystem" />

    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.SET_WALLPAPER" />
    <uses-permission android:name="android.permission.SET_WALLPAPER_HINTS" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.BIND_APPWIDGET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.BROADCAST_STICKY"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
    <uses-permission android:name="com.android.launcher.permission.WRITE_SETTINGS" />
    <uses-permission android:name="com.android.launcher3.permission.READ_SETTINGS" />
    <uses-permission android:name="com.android.launcher3.permission.WRITE_SETTINGS" />
    <uses-permission android:name="com.android.launcher3.permission.RECEIVE_LAUNCH_BROADCASTS" />
    <uses-permission android:name="com.android.launcher3.permission.RECEIVE_FIRST_LOAD_BROADCAST" />



    <application
        android:name=".App"
        android:hardwareAccelerated="true"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_launcher_name"
        android:roundIcon="@mipmap/ic_launcher"
        android:theme="@style/AppTheme"
        android:supportsRtl="true"
        android:restoreAnyVersion="true">
        <receiver android:name=".activities.BroadcastReceiverOnBootComplete">
            <intent-filter>
                <action android:name="com.simplemobiletools.applauncher.sendbroadcast" />
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.DEFAULT" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
            </intent-filter>
        </receiver>
        <activity
            android:launchMode="singleTask"
            android:clearTaskOnLaunch="true"
            android:stateNotNeeded="true"
            android:windowSoftInputMode="adjustPan"
            android:screenOrientation="nosensor"
            android:resumeWhilePausing="true"
            android:taskAffinity=""
            android:enabled="true"

            android:name=".activities.SplashActivity"
            android:theme="@style/SplashTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.HOME" />
                <category android:name="android.intent.category.LAUNCHER" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.MONKEY"/>
            </intent-filter>
        </activity>

        <activity android:name=".activities.MainActivity"/>

        <activity
            android:name=".activities.SettingsActivity"
            android:label="@string/settings"
            android:parentActivityName=".activities.MainActivity"/>

        <activity
            android:name="com.simplemobiletools.commons.activities.AboutActivity"
            android:label="@string/about"
            android:parentActivityName=".activities.MainActivity"/>

        <activity
            android:name="com.simplemobiletools.commons.activities.LicenseActivity"
            android:label="@string/third_party_licences"
            android:parentActivityName="com.simplemobiletools.commons.activities.AboutActivity"/>

        <activity
            android:name="com.simplemobiletools.commons.activities.CustomizationActivity"
            android:label="@string/customize_colors"
            android:parentActivityName=".activities.SettingsActivity"/>

    </application>
</manifest>

使用BroadcastReceiver的MainActivity

class MainActivity : SimpleActivity(), RefreshRecyclerViewListener {

    private var launchers = ArrayList<AppLauncher>()
    private var mStoredPrimaryColor = 0
    private var mStoredTextColor = 0
    private var mStoredUseEnglish = false
    private var receiver: BroadcastReceiver? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        appLaunched()
        setupLaunchers()
        checkWhatsNewDialog()
        storeStateVariables()
        configureReceiver()

        fab.setOnClickListener {
            AddAppLauncherDialog(this, launchers) {
                setupLaunchers()
            }
        }
    }

    override fun onDestroy() {
        // super.onDestroy()
        unregisterReceiver(receiver)
    }

    override fun onResume() {
        super.onResume()
        if (mStoredUseEnglish != config.useEnglish) {
            restartActivity()
            return
        }

        if (mStoredTextColor != config.textColor) {
            getGridAdapter()?.updateTextColor(config.textColor)
        }

        if (mStoredPrimaryColor != config.primaryColor) {
            getGridAdapter()?.updatePrimaryColor(config.primaryColor)
        }

        updateTextColors(coordinator_layout)
    }

    override fun onPause() {
        super.onPause()
        storeStateVariables()
    }

    private fun configureReceiver() {
        val filter = IntentFilter()
        filter.addAction("com.simplemobiletools.applauncher.sendbroadcast")
        filter.addAction("android.intent.action.ACTION_POWER_DISCONNECTED")
        filter.addAction("android.intent.action.BOOT_COMPLETED")
        receiver = BroadcastReceiverOnBootComplete()
        registerReceiver(receiver, filter)
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.settings -> launchSettings()
            R.id.about -> launchAbout()
            else -> return super.onOptionsItemSelected(item)
        }
        return true
    }

    private fun launchSettings() {
        startActivity(Intent(applicationContext, SettingsActivity::class.java))
    }

    private fun launchAbout() {
        startAboutActivity(R.string.app_name, LICENSE_KOTLIN or LICENSE_MULTISELECT or LICENSE_STETHO, BuildConfig.VERSION_NAME)
    }

    private fun getGridAdapter() = launchers_grid.adapter as? LaunchersAdapter

    private fun setupLaunchers() {
        launchers = dbHelper.getLaunchers()
        checkInvalidApps()
        val adapter = LaunchersAdapter(this, launchers, this, launchers_grid) {
            val launchIntent = packageManager.getLaunchIntentForPackage((it as AppLauncher).packageName)
            if (launchIntent != null) {
                startActivity(launchIntent)
                finish()
            } else {
                val url = "https://play.google.com/store/apps/details?id=${it.packageName}"
                val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                startActivity(intent)
            }
        }
        adapter.setupDragListener(true)
        launchers_grid.adapter = adapter
    }

    private fun checkInvalidApps() {
        val invalidIds = ArrayList<String>()
        for ((id, name, packageName) in launchers) {
            val launchIntent = packageManager.getLaunchIntentForPackage(packageName)
            if (launchIntent == null && !packageName.isAPredefinedApp()) {
                invalidIds.add(id.toString())
            }
        }
        dbHelper.deleteLaunchers(invalidIds)
        launchers = launchers.filter { !invalidIds.contains(it.id.toString()) } as ArrayList<AppLauncher>
    }

    private fun storeStateVariables() {
        config.apply {
            mStoredPrimaryColor = primaryColor
            mStoredTextColor = textColor
            mStoredUseEnglish = useEnglish
        }
    }

    override fun refreshItems() {
        setupLaunchers()
    }

    private fun checkWhatsNewDialog() {
        arrayListOf<Release>().apply {
            add(Release(7, R.string.release_7))
            checkWhatsNew(this, BuildConfig.VERSION_CODE)
        }
    }
}

1 个答案:

答案 0 :(得分:1)

因为我发现了概率; em在这里缺少设置

android:enabled="true"
android:stopWithTask="false"

所以它应该像

<receiver android:name=".activities.BroadcastReceiverOnBootComplete"   android:enabled="true"
            android:stopWithTask="false" >
            <intent-filter>
                <action android:name="com.simplemobiletools.applauncher.sendbroadcast" />
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.DEFAULT" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
            </intent-filter>
        </receiver>