android: use Intent.ACTION_BOOT_COMPLETED or …?

2019-08-18 18:21发布

In the AndroidManifest file, I want to capture the BOOT_COMPLETED event when the user re-boots their device. I am adding this permission:

"uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"

I have seen two "intent-filters" used by others on Stackoverflow:

"Intent.ACTION_BOOT_COMPLETED" and

"android.intent.action.BOOT_COMPLETED"

What is the preferred action string here? Please advise and explain.

2条回答
对你真心纯属浪费
2楼-- · 2019-08-18 18:32

Here is a complete solution:

Set the permission in the manifest:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

You need a receiver to run when your system restarts so something like this:

public class StartMyActivityAtBootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
           // everything here executes after system restart
        }
    }
}

Include this receiver in your manifest like below:

<receiver
    android:name=".service.StartMyActivityAtBootReceiver"
    android:label="StartMyServiceAtBootReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-08-18 18:44

Intent.ACTION_BOOT_COMPLETED == android.intent.action.BOOT_COMPLETED

They're both the same, because if you look into what the value of Intent.ACTION_BOOT_COMPLETED is, you'll see that it's android.intent.action.BOOT_COMPLETED.

Typically in the Manifest, you'll use android.intent.action.BOOT_COMPLETED due to Intent.ACTION_BOOT_COMPLETED being Java code rather than xml.

But in your code, you can use Intent.ACTION_BOOT_COMPLETED as an alternative due to it being much easier to remember.

查看更多
登录 后发表回答