如何在启动时启动我的应用程序? [英] How do I start my app on startup?
问题描述
我尝试使用此链接中的示例代码,但它似乎已过时,并且那没起效.那么,当Android完成启动后,我需要进行哪些更改以及使我的应用程序自动启动哪些文件?
I tried using the sample code in this link but it seems outdated and it did not work. So what changes do I have to make and to what files to have my app start automatically when Android finishes booting up?
推荐答案
首先,您需要AndroidManifest.xml
中的许可权:
First, you need the permission in your AndroidManifest.xml
:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
此外,在您的AndroidManifest.xml
中,定义您的服务并收听 BOOT_COMPLETED 操作:
Also, in yourAndroidManifest.xml
, define your service and listen for the BOOT_COMPLETED action:
<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 操作并启动服务的接收器.
Then you need to define the receiver that will get the BOOT_COMPLETED action and start your service.
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);
}
}
}
现在,当手机启动时,您的服务应已运行.
And now your service should be running when the phone starts up.
这篇关于如何在启动时启动我的应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!