问题
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.
回答1:
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.
回答2:
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>
来源:https://stackoverflow.com/questions/51295044/android-use-intent-action-boot-completed-or