我一直试图在设备在android上启动时启动一项服务,但我无法让它工作。我在网上看了一些链接,但没有一个代码工作。我是不是忘了什么?
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");
}
}
正如@Damian评论的那样,这个帖子里的所有答案都是错误的。手动这样做会有服务在设备进入睡眠状态时中途停止的风险。你需要先获得一个尾流锁。幸运的是,支持库给了我们一个类来做这件事:
public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// This is the Intent to deliver to our service.
Intent service = new Intent(context, SimpleWakefulService.class);
// Start the service, keeping the device awake while it is launching.
Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
startWakefulService(context, service);
}
}
然后,在你的服务中,确保释放唤醒锁:
@Override
protected void onHandleIntent(Intent intent) {
// At this point SimpleWakefulReceiver is still holding a wake lock
// for us. We can do whatever we need to here and then tell it that
// it can release the wakelock.
...
Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
SimpleWakefulReceiver.completeWakefulIntent(intent);
}
不要忘记在mainfest中添加WAKE_LOCK权限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
这就是我所做的
1. 我创建了Receiver类
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//whatever you want to do on boot
Intent serviceIntent = new Intent(context, YourService.class);
context.startService(serviceIntent);
}
}
2.在清单中
<manifest...>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application...>
<receiver android:name=".BootReceiver" android:enabled="true" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
...
3.你需要在MainActivity中“设置”接收器,它可能在onCreate中
...
final ComponentName onBootReceiver = new ComponentName(getApplication().getPackageName(), BootReceiver.class.getName());
if(getPackageManager().getComponentEnabledSetting(onBootReceiver) != PackageManager.COMPONENT_ENABLED_STATE_ENABLED)
getPackageManager().setComponentEnabledSetting(onBootReceiver,PackageManager.COMPONENT_ENABLED_STATE_ENABLED,PackageManager.DONT_KILL_APP);
...
这是我从ApiDemos中学到的最后一个步骤