如何在后台运行 Android 应用程序? [英] How to run an android app in background?

查看:51
本文介绍了如何在后台运行 Android 应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码会在系统启动后自动运行应用程序,但应用程序会在按下后退按钮后关闭.

This code will run an app automatically after booting the system, but the app will close after pressing the back button.

如果应用程序通过点击它的图标正常运行.即使按下后退按钮或运行其他应用程序,它也会继续运行.

If the app is run normally by clicking it's icon. It will continuously run even after pressing the back button or running other apps.

public class AutoBoot 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);          
    }
}

我的问题是,如何让这个自动运行代码在按下后退按钮或运行其他应用程序后继续运行?

My question is, how to make this auto run code to continuously run even after pressing the back button or running other apps?

推荐答案

你或许可以开始一个Service 如果您希望您的应用程序在后台运行.这就是 Android 中的 Service 的用途 - 在后台运行并执行长时间操作.

You can probably start a Service here if you want your Application to run in Background. This is what Service in Android are used for - running in background and doing longtime operations.

UDPATE

您可以使用 START_STICKY 使您的服务持续运行.

You can use START_STICKY to make your Service running continuously.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    handleCommand(intent);
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return START_STICKY;
}

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

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