---
title: "android 清空之前task中的activity"
author: "hellorheaven"
date: "2016-09-29T14:15:14Z"
tags: []
categories: ["移动开发"]
slug: "android-task-activity"
draft: false
lastmod: "2016-09-29T14:19:40Z"
id: 2327814
url: "https://hellorheaven.iteye.com/blog/2327814"
---

开发过程有个场景：关闭之前所有activity,跳转到登录页

以前是activity都放到一个list里面，退出应用的时候遍历列表，逐个finish

换种实现方式

跳转登录页的intent添加两个flag  
```java
Intent.FLAG_ACTIVITY_CLEAR_TASK

```
 

```java
Intent.FLAG_ACTIVITY_NEW_TASK
```


```java

	Intent intent = new Intent(this, TestCActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
```




当然如果登录页的launchMode为singleTask的话，就不需要
```java
Intent.FLAG_ACTIVITY_NEW_TASK
```

(要么在manifest文件中声明，要么在intent中添加flag,二者择一即可)

看下google文档

```java

     * If set in an Intent passed to {@link Context#startActivity Context.startActivity()},
     * this flag will cause any existing task that would be associated with the
     * activity to be cleared before the activity is started.  That is, the activity
     * becomes the new root of an otherwise empty task, and any old activities
     * are finished.  This can only be used in conjunction with {@link #FLAG_ACTIVITY_NEW_TASK}.

```


cet-4的基本能看懂吧~

<span style="color:red">备注 api level 要大于 11</span>