首先,你需要在你的AndroidManifest.xml
中设置权限。
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
同时,在你的AndroidManifest.xml
中,定义你的服务并监听BOOT_COMPLETED动作。
<service android:name=".MyService" android:label="My Service">
<intent-filter>
<action android:name="com.myapp.MyService" />
</intent-filter>
</service>
<receiver
android:name=".receiver.StartMyServiceAtBootReceiver"
android:label="StartMyServiceAtBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
然后,你需要定义接收器,以获得BOOT_COMPLETED动作并启动你的服务。
public class StartMyServiceAtBootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Intent serviceIntent = new Intent(context, MyService.class);
context.startService(serviceIntent);
}
}
}
现在你的服务应该在手机启动时运行。
听听ACTION_BOOT_COMPLETE,然后做你需要做的事。 这里有一个代码片段。
更新:
答案上的原始链接已经失效,所以根据评论,这里是链接的代码,因为当链接失效时,没有人会错过这个代码。
在AndroidManifest.xml(应用程序部分)。
<receiver android:enabled="true" android:name=".BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
...
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
...
public class BootUpReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, MyActivity.class); //MyActivity can be anything which you want to start on bootup...
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}