美文网首页
关于service启动Activity

关于service启动Activity

作者: 小庄bb | 来源:发表于2018-11-12 22:33 被阅读55次

前言

在讨论今天的内容之前,我们先看一段代码:

  • TextService.java
Intent intent = new Intent(this, SecondActivity.class);
this.startActivity(intent);

请问?上述代码是否正确?



没错,这就是一个简单的Activity启动。此时,机智的童鞋A默默的祭出demo大法,安装至自己的魅族16th(android8.0)然后发现流畅运行,毫无障碍。然后童鞋B飞速效仿之,一个分毫不差的demo在低端三星机(Android4.4)上安装后,结果被无情的送了一个异常。

java.lang.RuntimeException: Error receiving broadcast Intent { act=com....}
...
Caused by: android.util.AndroidRuntimeException: 
Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

从上面报错信息我们可以知道Intent缺少FLAG_ACTIVITY_NEW_TASK flag信息,添加后解决。

Intent intent = new Intent(this, SecondActivity.class);
intent .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
this.startActivity(intent);

正文

那么,看到这里就有了一些疑问。

  • 为什么Activity启动Activity时就没有需不需要添加的问题
  • 为什么Service有时候需要添加flog,有的不需要添加?
  • 什么时候需要添加而什么时候不用添加?或者说到底添加是对的还是不添加是对?
  • 添加了以后和正常启动有什么区别,会造成哪些影响。
  • 为什么这么设计。

一、 Context的继承关系图

首先我们来看一张图,这张图表示了Context里的基本继承关系。


Context继承关系图

我们可以看到:

  1. 最上面的是Context,它其实是一个抽象类,他有两个重要的子类ContextImpl和ContextWrapper。
  2. ContextImpl,是Context功能实现的主要类。
  3. ContextWrapper,顾名思义它就是一个包装类,主要功能都是通过调用ContextImpl去实现的。
  4. ContextThemeWrapper,包括一些主题的包装,由于
    Service没有主题,所以直接继承ContextWrapper;但是Activity就需要继承ContextThemeWrapper。

二、启动activity方法startActivity

看了上面的Context继承图,相信大家对为什么Activity启动Activity和Service启动Activity有差异有了一定的想法。那么到底差异在哪里呢?

首先我们看下Activity是如何启动的,当Activity启动Activity时会调用Activity.startActivity(intent)

Activity
    @Override
    public void startActivity(Intent intent) {
        this.startActivity(intent, null);
    }
    //最终会调
    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);
            ......//省略无关代码
        } else {
            ......//省略无关代码
        }
    }

这里的mParent是ActivityThread.scheduleLaunchActivity()里的ActivityClientRecord传给他的,默认为空。而mInstrumentation.execStartActivity方法就表示开始启动Activity了。

上面我们可以看到,activity调用startActivity时并不需要flog。但是service到底是需要还是不需要flog呢?为什么会出现有时候需要有时候不需要的情况?

来!关门,放狗!


不好意思!是放图!


Activity启动权限图

上图是Activity启动权限图,我们可以看到,除了Activiy以外其他组件都是不允许启动Activity的。但是上述A同学的魅族16th(android8.0)却能流畅运行,这是为什么呢?

那么Sevice启动Activity的流程具体到底是怎样呢?来看一下源码:
像Service,BroadcastReceiver,Application等都是ContextWrapper的子类,调用startActivity()时会调用ContextWrapper的startActivity()

ContextWrapper
    @Override
    public void startActivity(Intent intent) {
        mBase.startActivity(intent);
    }

这个mBase就是ContextImpl.这个ContextImpl是在ActivityThread里赋值的:
Activity-->ActivityThread::performLaunchActivity()
Service-->ActivityThread::handleCreateService()
Application-->LoadedApk::makeApplication()
有兴趣的同学自行查看.

那我们来看下ContextImpl的startActivity().
先看低版本的(android6.0)

ContextImpl
    @Override
    public void startActivity(Intent intent) {
        warnIfCallingFromSystemProcess();
        startActivity(intent, null);
    }

    @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);
    }

我们只需要关注这个判断条件(intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0。很简单,就是非Activity的Context启动Activity时如果不给intent设置FLAG_ACTIVITY_NEW_TASK就会报错。那我们就可以通过给intent设置FLAG_ACTIVITY_NEW_TASK,来解决B同学的问题。

然后我们来看看高版本(android 8.0)

ContextImpl
    @Override
    public void startActivity(Intent intent) {
        warnIfCallingFromSystemProcess();
        startActivity(intent, null);
    }

    @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);
    }

和上面的android6.0相比。判断条件里多了一些判断options != null && ActivityOptions.fromBundle(options).getLaunchTaskId() == -1这里因为options这个参数传入的就是null,也就是说options != null && ActivityOptions.fromBundle(options).getLaunchTaskId() == -1为false。会直接绕过异常抛出,这里应该是一个bug。就算不给intent设置FLAG_ACTIVITY_NEW_TASK,也会顺利启动。查了一下,这个更改是从android(7.0)开始的。

android(9.0)

ContextImpl
    @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. A bug was existed between N and O-MR1 which allowed this to work. We
        // maintain this for backwards compatibility.
        final int targetSdkVersion = getApplicationInfo().targetSdkVersion;

        if ((intent.getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) == 0
                && (targetSdkVersion < Build.VERSION_CODES.N
                        || targetSdkVersion >= Build.VERSION_CODES.P)
                && (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);
    }

查看android(9.0)源码,这里判断条件修改为(intent.getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) == 0 && (targetSdkVersion < Build.VERSION_CODES.N || targetSdkVersion >= Build.VERSION_CODES.P) && (options == null || ActivityOptions.fromBundle(options).getLaunchTaskId() == -1)貌似已经解决了这个问题。暂时没有条件测试,有条件的同学可以测试一下。

通过上面我们可以看到,其实是因为google的大佬,在android7.0 android8.0版本出现了一个bug导致程序逻辑绕过了flog参数的验证。所以,对应的正确逻辑应该如Activity启动权限图所示,其他组件要启动actvicity是需要添加flog标记的。

FLAG_ACTIVITY_NEW_TASK导致的问题

既然添加了flog后其他组件就可以正常调用startActivity启动Activity。那为什么activity启动权限表上除了Activity其他组件都是NO!这样调用与我们正常使用Activity调用有什么区别呢?会不会出现一些其他问题?答案是会!
首先我们需要搞清楚,我们添加的flog的作用。给Intent.addFlogs(Intent.FLAG_ACTIVITY_NEW_TASK)就代表着,启动的Activity会位于一个新的Task。举个例子,如果你在电话本里启动的,那么你的最近任务列表就会有两个电话本,因为有两个task嘛。那怎么解决呢?
很简单,将需要其他组件启动的Activity配置属性android:excludeFromRecents=”true”,那么该Activity将不会显示在最近任务列表中。

android 为什么要这样设计

为什么要将activity与其他组件区分对待呢?同样的我们举个栗子。
假设:我们有这样一个需求:
我们的电话本里有一个Service,然后它执行5分钟后,将启动一个Activity.那么很有可能5分钟以后已经不在电话本页面了,假设在浏览器页面了,此时的Task就是浏览器Task,如果这个Activity在当前Task的话,也就是在浏览器Task的话。那么用户会感觉莫名其妙,因为这个Activity本来是属于电话本的。所以对于Service而言,干脆强制定义启动的Activity需要创建一个新的Task,这样设计会比较合理。

Service启动Dialog

由于Dialog是依赖于Activity存在的,所以service启动Dialog主要有两种方法:

  1. 首先启动一个半透明的Activity,然后在Activity里启动Dialog。
  2. 使用WindowManage实现
    使用WindowManage应该注意,此时的Dialog是SYSTEM级别的,如果程序在后台启动这个Dialog,Dialog会浮在桌面上。(使用小米等有自己权限管理的系统时,需要申请一定权限才可以在桌面显示这个 Dialog,否则只能在自己 APP 前台时才显示)
使用WindowsManage实现
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("是否接受文件?")
.setPositiveButton("是", new DialogInterface.OnClickListener() {
@Override
publicvoid onClick(DialogInterface dialog, int which) {
}
}).setNegativeButton("否", new OnClickListener() {
@Override
publicvoid onClick(DialogInterface dialog, int which) {
}
});
AlertDialog ad = builder.create();
// ad.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG); //系统中关机对话框就是这个属性
ad.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
ad.setCanceledOnTouchOutside(false); //点击外面区域不会让dialog消失
ad.show();

权限

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />11
使用Activity实现

Activity主题

<style name="DialogTransparent" parent="@android:style/Theme.Dialog">
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowAnimationStyle">@android:style/Animation</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowIsFloating">false</item>
        <item name="android:windowIsTranslucent">true</item>
    </style>

或者直接使用

@android:style/Theme.Dialog

文章来自:
https://www.jianshu.com/p/aa4ec93cc194
https://blog.csdn.net/fang323619/article/details/74388804

相关文章

网友评论

      本文标题:关于service启动Activity

      本文链接:https://www.haomeiwen.com/subject/creyiftx.html