Trying to start a service on boot on Android

2018-12-31 01:08发布

I've been trying to start a service when a device boots up on android, but I cannot get it to work. I've looked at a number of links online but none of the code works. Am I forgetting something?

AndroidManifest.xml

<receiver
    android:name=".StartServiceAtBootReceiver"
    android:enabled="true"
    android:exported="false"
    android:label="StartServiceAtBootReceiver" >
    <intent-filter>
        <action android:name="android.intent.action._BOOT_COMPLETED" />
    </intent-filter>
</receiver>

<service
    android:name="com.test.RunService"
    android:enabled="true" />

BroadcastReceiver

public void onReceive(Context context, Intent intent) {
    if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
        Intent serviceLauncher = new Intent(context, RunService.class);
        context.startService(serviceLauncher);
        Log.v("TEST", "Service loaded at start");
    }
}

16条回答
还给你的自由
2楼-- · 2018-12-31 01:24

If you're using Android Studio and you're very fond of auto-complete then I must inform you, I'm using Android Studio v 1.1.0 and I used auto-complete for the following permission

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

And Android Studio Auto-completedRECEIVE_BOOT_COMPLETED all in lower-case like receive_boot_completed and I kept pulling my hair out because I'd already ticked out my checklist for things to do to start service at boot. I just confirmed again

Android Studio DOES auto-complete this permission in lower-case.

查看更多
听够珍惜
3楼-- · 2018-12-31 01:24

I faced with this problem if i leave the empty constructor in the receiver class. After the removing the empty contsructor onRreceive methos started working fine.

查看更多
还给你的自由
4楼-- · 2018-12-31 01:25

As an additional info: BOOT_COMPLETE is sent to applications before external storage is mounted. So if application is installed to external storage it won't receive BOOT_COMPLETE broadcast message.

More details here in section Broadcast Receivers listening for "boot completed"

查看更多
姐姐魅力值爆表
5楼-- · 2018-12-31 01:27

Along with

<action android:name="android.intent.action.BOOT_COMPLETED" />  

also use,

<action android:name="android.intent.action.QUICKBOOT_POWERON" />

HTC devices dont seem to catch BOOT_COMPLETED

查看更多
墨雨无痕
6楼-- · 2018-12-31 01:27

I think your manifest needs to add:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
查看更多
一个人的天荒地老
7楼-- · 2018-12-31 01:28

I found out just now that it might be because of Fast Boot option in Settings > Power

When I have this option off, my application receives a this broadcast but not otherwise.

By the way, I have Android 2.3.3 on HTC Incredible S.

Hope it helps.

查看更多
登录 后发表回答