如何自动启动 Android 应用程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1056570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:39:15  来源:igfitidea点击:

How to Auto-start an Android Application?

android

提问by Rajapandian

I'm not sure how to autostart an android application after the android emulator completes its booting. Does anyone have any code snippets that will help me?

我不确定如何在 android 模拟器完成启动后自动启动一个 android 应用程序。有没有人有任何代码片段可以帮助我?

回答by Krzysztof Wolny

You have to add a manifest permission entry:

您必须添加清单权限条目:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

(of course you should list all other permissions that your app uses).

(当然,您应该列出您的应用程序使用的所有其他权限)。

Then, implement BroadcastReceiver class, it should be simple and fast executable. The best approach is to set an alarm in this receiver to wake up your service (if it's not necessary to keep it running ale the time as Prahast wrote).

然后,实现 BroadcastReceiver 类,它应该是简单快速的可执行文件。最好的方法是在这个接收器中设置一个闹钟来唤醒你的服务(如果没有必要让它在 Prahast 写的时间保持运行)。

public class BootUpReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context, MyService.class), PendingIntent.FLAG_UPDATE_CURRENT);
    am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + interval, interval, pi);
}}

Then, add a Receiver class to your manifest file:

然后,将 Receiver 类添加到您的清单文件中:

    <receiver android:enabled="true" android:name=".receivers.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>

回答by sandy

Edit your AndroidManifest.xmlto add RECEIVE_BOOT_COMPLETEDpermission

编辑您 AndroidManifest.xml的添加RECEIVE_BOOT_COMPLETED权限

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Edit your AndroidManifest.xmlapplication-part for below Permission

编辑您的 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>

Now write below in Activity.

现在写在下面的活动中。

public class BootUpReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
    Intent i = new Intent(context, MyActivity.class);  
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(i);  
}
}

回答by Prashast

If by autostart you mean auto start on phone bootup then you should register a BroadcastReceiver for the BOOT_COMPLETEDIntent. Android systems broadcasts that intent once boot is completed.

如果自动启动是指在手机启动时自动启动,那么您应该为BOOT_COMPLETEDIntent注册一个 BroadcastReceiver 。一旦启动完成,Android 系统就会广播该意图。

Once you receive that intent you can launch a Service that can do whatever you want to do.

一旦你收到这个意图,你就可以启动一个可以做任何你想做的事情的服务。

Keep note though that having a Service running all the time on the phone is generally a bad idea as it eats up system resources even when it is idle. You should launch your Service / application only when needed and then stop it when not required.

请注意,让服务一直在电话上运行通常是一个坏主意,因为即使它空闲也会消耗系统资源。您应该只在需要时启动您的服务/应用程序,然后在不需要时停止它。

回答by nafsaka

I always get in here, for this topic. I'll put my code in here so i (or other) can use it next time. (Phew hate to search into my repository code).

我总是在这里讨论这个话题。我会把我的代码放在这里,以便我(或其他人)下次可以使用它。(Phew 讨厌搜索我的存储库代码)。

Add the permission:

添加权限:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Add receiver and service:

添加接收器和服务:

    <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>
    <service android:name="Launcher" />

Create class Launcher:

创建类启动器:

public class Launcher extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        new AsyncTask<Service, Void, Service>() {

            @Override
            protected Service doInBackground(Service... params) {
                Service service = params[0];
                PackageManager pm = service.getPackageManager();
                try {
                    Intent target = pm.getLaunchIntentForPackage("your.package.id");
                    if (target != null) {
                        service.startActivity(target);
                        synchronized (this) {
                            wait(3000);
                        }
                    } else {
                        throw new ActivityNotFoundException();
                    }
                } catch (ActivityNotFoundException | InterruptedException ignored) {
                }
                return service;
            }

            @Override
            protected void onPostExecute(Service service) {
                service.stopSelf();
            }

        }.execute(this);

        return START_STICKY;
    }
}

Create class BootUpReceiverto do action after android reboot.

创建类BootUpReceiver以在 android 重启后执行操作。

For example launch MainActivity:

例如启动 MainActivity:

public class BootUpReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent target = new Intent(context, MainActivity.class);  
        target.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(target);  
    }
}