Android: 如何在后台启动Activity

15

通常我使用以下代码启动一个活动:

Intent i = new Intent(context, MyActivity.class);  
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);  

但是,我该如何启动活动以使其保留在后台?


如果需要在后台执行某些操作,请使用Service而不是Activity。 - Selvin
1
正如评论和答案中所说,您不能启动一个活动使其保持在后台(您应该使用服务来实现)。 - Leeeeeeelo
1
我知道服务是用于后台进程的。但问题并不是“我应该使用Activity进行后台进程”,而只是为了测试是否可以通过提前启动Activity来加快其初始化时间。看起来,如果它是普通的Activity,这是不可能的。感谢所有花时间回答问题的人! - digitalfootmark
4个回答

8

7
为了让一个活动在后台运行,可以使用服务。创建一个后台服务如下所示:
import android.app.Service;
import android.content.Intent;
import android.os.Binder;

import android.os.IBinder;

public class BackgroundService extends Service {


    private final IBinder mBinder = new LocalBinder();

    public class LocalBinder extends Binder {
        BackgroundService getService() {
            return BackgroundService.this;
        }
    }


    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
}

在您的主活动的oncreate()中像这样调用服务 -
 startService(new Intent( MainActivity.this,BackgroundService.class));

在主活动的onCreate()中添加this.finish();以关闭该活动。 - Avinash R

2

你可以做三件事情

如果你想在后台执行长时间运行的任务并更新UI,请使用Asyntask。 如果你只想在后台执行长时间运行的任务,使用Intentservice。 如果你需要一些不太重的背景任务,使用Services。


服务在UI线程中运行,因此如果您在其上使用重任务,则应用程序可能会挂起。您可以使用具有一些工作线程的服务。 - Nitin Gupta
使用 IntentService,一旦启动,即使 UI 被关闭或不在运行,它也会继续运行吗? - BTR Naidu

0

Activity通常是用来展示给用户的。如果您不需要任何UI,也许根本不需要子类化Activity。考虑使用Service或IntentService来完成您的任务。或者您可以将Activity的主题设置为.NoDisplay


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接