通常我使用以下代码启动一个活动:
Intent i = new Intent(context, MyActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
但是,我该如何启动活动以使其保留在后台?
通常我使用以下代码启动一个活动:
Intent i = new Intent(context, MyActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
但是,我该如何启动活动以使其保留在后台?
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;
}
}
startService(new Intent( MainActivity.this,BackgroundService.class));
onCreate()
中添加this.finish();
以关闭该活动。 - Avinash R你可以做三件事情
如果你想在后台执行长时间运行的任务并更新UI,请使用Asyntask。 如果你只想在后台执行长时间运行的任务,使用Intentservice。 如果你需要一些不太重的背景任务,使用Services。
Activity通常是用来展示给用户的。如果您不需要任何UI,也许根本不需要子类化Activity。考虑使用Service或IntentService来完成您的任务。或者您可以将Activity的主题设置为.NoDisplay
。