activity的startActivity和context的startActivity区别

相信Android开发都遇到过这样一个报错信息

04-09 15:55:08.165: E/AndroidRuntime(3403): android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

解决办法也很简单,就是在非Activity的Context调用startActivity方法时,Intent添加一个FLAG_ACTIVITY_NEW_TASK的flag,代码如下

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

但是细心的同学会发现Android7.0及以上的机型即使没有添加以上代码,也不会崩溃。这是怎么回事呢?

这就涉及到activity的startActivity和context的startActivity方法之间的区别,Activity也是Context的子类,但是Activity本身实现了startActivity方法,所以两个是不同的。

activity的startActivity方法最终会调用Activity类的startActivityForResult方法,代码如下

public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
           @Nullable Bundle options) {
       if (mParent == null) {
           options = transferSpringboardActivityOptions(options);
           Instrumentation.ActivityResult ar =
               mInstrumentation.execStartActivity(
                   this, mMainThread.getApplicationThread(), mToken, this,
                   intent, requestCode, options);
           if (ar != null) {
               mMainThread.sendActivityResult(
                   mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                   ar.getResultData());
           }
           if (requestCode >= 0) {
               // If this start is requesting a result, we can avoid making
               // the activity visible until the result is received.  Setting
               // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
               // activity hidden during this time, to avoid flickering.
               // This can only be done when a result is requested because
               // that guarantees we will get information back when the
               // activity is finished, no matter what happens to it.
               mStartedActivity = true;
           }

           cancelInputsAndStartExitTransition(options);
           // TODO Consider clearing/flushing other event sources and events for child windows.
       } else {
           if (options != null) {
               mParent.startActivityFromChild(this, intent, requestCode, options);
           } else {
               // Note we want to go through this method for compatibility with
               // existing applications that may have overridden it.
               mParent.startActivityFromChild(this, intent, requestCode);
           }
       }
   }

context的 startActivity方法最终会调用ContextImpl的startActivity方法,代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
@Override
public void startActivity(Intent intent, Bundle options) {
warnIfCallingFromSystemProcess();
if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
throw new AndroidRuntimeException(
"Calling startActivity() from outside of an Activity "
+ " context requires the FLAG_ACTIVITY_NEW_TASK flag."
+ " Is this really what you want?");
}
mMainThread.getInstrumentation().execStartActivity(
getOuterContext(), mMainThread.getApplicationThread(), null,
(Activity) null, intent, -1, options);
}

7.0及以下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Override
public void startActivity(Intent intent, Bundle options) {
warnIfCallingFromSystemProcess();

// Calling start activity from outside an activity without FLAG_ACTIVITY_NEW_TASK is
// generally not allowed, except if the caller specifies the task id the activity should
// be launched in.
if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0
&& options != null && ActivityOptions.fromBundle(options).getLaunchTaskId() == -1) {
throw new AndroidRuntimeException(
"Calling startActivity() from outside of an Activity "
+ " context requires the FLAG_ACTIVITY_NEW_TASK flag."
+ " Is this really what you want?");
}
mMainThread.getInstrumentation().execStartActivity(
getOuterContext(), mMainThread.getApplicationThread(), null,
(Activity) null, intent, -1, options);
}

从上面代码可以看出,Activity的startActivity方法是不会抛出文章开始说的那个错的;问题集中在非Activity的Context调用startActivity方法,在7.0之前如果Intent没有添加flag:FLAG_ACTIVITY_NEW_TASK,程序是必崩的,7.0及以上如果调用startActivity(intent)方法,是不会崩的,因为此时options为空。一般为了兼容7.0以下版本,我们还是得添加flag的。

1
startActivity(intent, null);

注意7.0增加了两个判断条件

1
2
3
4
5
6
7
if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0
&& options != null && ActivityOptions.fromBundle(options).getLaunchTaskId() == -1) {
throw new AndroidRuntimeException(
"Calling startActivity() from outside of an Activity "
+ " context requires the FLAG_ACTIVITY_NEW_TASK flag."
+ " Is this really what you want?");
}

到这里基本上文章就该结束了,但是我们项目在线上还是遇到文章开始说的那个问题,有一些崩溃,都是7.0以下的机型。经过一番寻找,终于定位到有问题的代码,原因是我们用到了Intent的一个方法createChooser(Intent target, CharSequence title)

1
2
3
4
5
6
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, text);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.setType("text/plain");
Utils.getContext().startActivity(Intent.createChooser(shareIntent, "分享到"));

从代码上看到我们明明给Intent添加了flag,还是会崩溃

1
shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

我们跟进Intent.createChooser方法里看看

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public static Intent createChooser(Intent target, CharSequence title, IntentSender sender) {
Intent intent = new Intent(ACTION_CHOOSER);
intent.putExtra(EXTRA_INTENT, target);
if (title != null) {
intent.putExtra(EXTRA_TITLE, title);
}

if (sender != null) {
intent.putExtra(EXTRA_CHOSEN_COMPONENT_INTENT_SENDER, sender);
}

// Migrate any clip data and flags from target.
int permFlags = target.getFlags() & (FLAG_GRANT_READ_URI_PERMISSION
| FLAG_GRANT_WRITE_URI_PERMISSION | FLAG_GRANT_PERSISTABLE_URI_PERMISSION
| FLAG_GRANT_PREFIX_URI_PERMISSION);
if (permFlags != 0) {
ClipData targetClipData = target.getClipData();
if (targetClipData == null && target.getData() != null) {
ClipData.Item item = new ClipData.Item(target.getData());
String[] mimeTypes;
if (target.getType() != null) {
mimeTypes = new String[] { target.getType() };
} else {
mimeTypes = new String[] { };
}
targetClipData = new ClipData(null, mimeTypes, item);
}
if (targetClipData != null) {
intent.setClipData(targetClipData);
intent.addFlags(permFlags);
}
}

return intent;
}

首先这个方法先把原Intent存到新Intent的extra上,

1
intent.putExtra(EXTRA_INTENT, target);

然后permFlags值为0,就这样,新Intent的flag就没了,所以返回来的Intent的flag值为0,虽然extra里的Intent的flag值为Intent.FLAG_ACTIVITY_NEW_TASK,但是没有,取flag值时不是从extra里的Intent取值。

1
2
3
int permFlags = target.getFlags() & (FLAG_GRANT_READ_URI_PERMISSION
| FLAG_GRANT_WRITE_URI_PERMISSION | FLAG_GRANT_PERSISTABLE_URI_PERMISSION
| FLAG_GRANT_PREFIX_URI_PERMISSION);

有点坑吧,所以如果使用了Intent.createChooser()方法后还得加上addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)

1
Utils.getContext().startActivity(Intent.createChooser(shareIntent, "分享到").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));

建议以后如果有非Activity的Context调用startActivity()方法,一定要用7.0以下的机型测试一下,我们手上的测试大部分是7.0的,加上那段代码的使用场景很少,所以导致了线上出现这个bug。

Java线程池

定义:java.util.concurrent.Executors提供了一个java.util.concurrent.Executor接口的实现用于创建线程池。一个线程池包括以下四个基本组成部分:

  1. 线程池管理器(ThreadPool): 用于创建并管理线程池,包括创建线程池,销毁线程池,添加新任务;
  2. 工作线程(PoolWorker): 线程池中线程,在没有任务时处于等待状态,可以循环的执行任务;
  3. 任务接口(Task): 每个任务必须实现的接口,以供工作线程调度任务的执行,它主要规定了任务的入口,任务执行完后的收尾工作,任务的执行状态等;
  4. 任务队列(TaskQueue): 用于存放没有处理的任务。提供一种缓冲机制。

使用线程池的好处:

  • 重用线程池中的线程,避免因为线程的创建和销毁所带来的性能开销。
  • 能有效控制线程池的最大并发数,避免大量的线程之间因互相抢占系统 资源而导致的阻塞现象。
  • 能够对线程进行简单的管理,并提供定时执行以及指定间隔循环执行等功能。

ThreadPoolExecutor

ThreadPoolExecutor是线程池的真正实现,它的构造方法提供了一系列参数来配置线程池,下面是ThreadPoolExecutor的参数最全的构造方法

1
2
3
4
5
6
7
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)

corePoolSize

​ 线程池的核心线程数,默认情况下,核心线程数会在线程池中一直存活,即使它们处于闲置状态。如果将ThreadPoolExecutor的allowCoreThreadTimeOut属性设置为true,那么闲置的核心线程在等待新任务到来时会有超时策略,这个时间间隔由keepAliveTime所指定,当等待时间超过keepAliveTime所指定的时长后,核心线程就会终止。

maximumPoolSize

​ 线程池所能容纳的最大线程数,当活动线程数达到这个数值后,后续的新任务将会被阻塞。

keepAliveTime

​ 非核心线程闲置时的超时时长,超过这个时长,非核心线程将会被回收。当ThreadPoolExecutor的allowCoreThreadTimeOut属性设置为true时,keepAliveTime同样会作用于核心线程。

unit

​ 用于指定keepAliveTime参数的时间单位,这是一个枚举,常用的有TimeUnit.MILLISECONDS(毫秒)、TimeUnit.SECONDS(秒)、TimeUnit.MINUTES(分钟)等。

workQueue

​ 线程池中的队列任务,通过线程池的execute方法提交的Runnable对象会存储在这个参数中。

threadFactory

​ 线程工厂,为线程池提供创建新新线程的功能。ThreadFactory是一个接口,它只有一个方法:Thread newThread(Runnable c)。

handler

​ 当线程池无法执行新任务时,这可能是由于任务队列已满或者是无法成功执行任务,这个时候ThreadPoolExecutor会调用handler的rejectExecution方法来通知调用者。RejectedExecutionHandler是一个接口,有四个实现类,CallerRunsPolicy、AbortPolicy、DiscardPolicy和DiscardOldestPolicy,其中AbortPolicy是默认值,它会直接抛出RejectedExecutionException,这个参数不常用。

ThreadPoolExecutor执行任务时大致遵循如下规则:

  1. 如果线程池中的线程数量未达到核心线程的数量,那么会直接启动一个核心线程来执行任务。
  2. 如果线程池中的线程数量已经达到或者超过核心线程的数量,那么任务会被插入到任务队列中排队等待执行。
  3. 如果在步骤2中无法将任务插入到任务队列中,这往往是由于任务队列已满,这个时候如果线程数量未达到线程池规定的最大值,那么会立刻启动一个非核心线程来执行任务。
  4. 如果步骤3中线程数量已经达到线程池规定的最大值,那么就拒绝执行 此任务,ThreadPoolExecutor会调用RejectedExecutionHandler的rejectExecution方法来通知调用者。

Executors

为了方便使用,Java提供了Executors工具类,Executors提供了几种具有不同功能特性的线程池,它们都直接或间接地通过配置ThreadPoolExecutor来实现自己的功能特性。

1.FixedThreadPool

1
2
3
4
5
6
7
8
9
10
11
12
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}

public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory){
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
}

​ 通过Executors.newFixedThread(nThreads)方法来创建。它是一种线程数量固定的线程池,当线程池处于空闲状态时,它们并不会被回收,除非线程池被关闭了。当所有的线程池都处于活动状态时,新任务都会处于等待状态,直到有线程空闲出来。由于FixedThreadPool只有核心线程并且这些核心线程不会被回收,这意味着它能够更加快速地响应外界的请求。FixedThreadPool只有核心线程并且这些核心线程 没有超时机制,另外任务队列也是没有大小限制的。

2.CachedThreadPool

1
2
3
4
5
6
7
8
9
10
11
12
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}

public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
threadFactory);
}

​ 通过Executors.newCachedThreadPool()方法来创建。它是一种线程数量不定的线程池,它只有非核心线程,并且其最大线程数为Integer.MAX_VALUE。由于Integer.MAX_VALUE是一个很大的数,实际上就相当于最大线程数可以任意大。当线程池中的线程都处于活动状态时,线程池会创建新的线程来处理新任务,否则就会利用空闲的线程来处理新任务。线程池中的空闲线程都有超时机制,这个超时时长为60秒,超过60秒闲置线程就会被回收。和FixedThreadPool不同的是,CachedThreadPool的任务队列其实相当于一个空集合,这将导致人和任务都会被立即执行,因为在这种场景下SynchronousQueue是无法插入任务的。SynchronousQueue是一个非常特殊的队列,在很多情况下可以把它简单理解为一个无法存储元素的队列,在实际中较少使用。从CachedThreadPool的特性来看,这类线程比较适合执行大量的耗时较少的任务。当整个线程池处于闲置状态时,线程池中的线程都会超时而被停止,这个时候CachedThreadPool之中实际上是没有任何线程的,它几乎不占用任何系统资源的。

3.ScheduledThreadPool

1
2
3
4
5
6
7
8
9
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}

public ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory) {
super(corePoolSize, Integer.MAX_VALUE,
DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
new DelayedWorkQueue(), threadFactory);
}

​ 通过Executors.newCachedThreadPool(corePoolSize)方法来创建。它的核心线程数量是固定的,而非核心线程数是没有限制的,并且当非核心线程闲置时会被立即回收。ScheduledThreadPool这类线程主要用于执行定时任务和具有固定周期的重复任务。

4.SingleThreadExecutor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}

public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory));
}

​ 通过Executors.newSingleThreadExecutor()方法来创建。这类线程池内部只有一个核心线程,它确保所有的任务都在同一个线程中按照顺序执行。SingleThreadExecutor的意义在于统一所有的外界任务到同一个线程中,这使得在这些任务之间不需要处理线程同步的问题。