当手机在 Android 上启动时如何启动我的应用程序? [英] How do I start my app when the phone starts on Android?

查看:32
本文介绍了当手机在 Android 上启动时如何启动我的应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用示例代码 在本教程中,但它似乎已经过时并且没有用.那么,当 Android 完成启动时,我必须进行哪些更改以及哪些文件才能让我的应用自动启动?

I tried using the sample code in this tutorial 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.

这篇关于当手机在 Android 上启动时如何启动我的应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆