Trying to start a service on boot on Android(尝试在 Android 上启动服务)
问题描述
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");
}
}
The other answers look good, but I thought I'd wrap everything up into one complete answer.
You need the following in your AndroidManifest.xml file:
In your
<manifest>element:<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />In your
<application>element (be sure to use a fully-qualified [or relative] class name for yourBroadcastReceiver):<receiver android:name="com.example.MyBroadcastReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver>(you don't need the
android:enabled,exported, etc., attributes: the Android defaults are correct)In
MyBroadcastReceiver.java:package com.example; public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Intent startServiceIntent = new Intent(context, MyService.class); context.startService(startServiceIntent); } }
From the original question:
- it's not clear if the
<receiver>element was in the<application>element - it's not clear if the correct fully-qualified (or relative) class name for the
BroadcastReceiverwas specified - there was a typo in the
<intent-filter>
这篇关于尝试在 Android 上启动服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:尝试在 Android 上启动服务
基础教程推荐
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
