子线程不可以更新UI吗

子线程不可以更新UI吗?(2019-11-05)

这里文章基于Android 系统8.0及以上版本分析子线程更新UI并没有报错的原因,其它版本并没有出现这种情况可以参考这篇文章子线程能更新UI吗。经常看到文章说不要在子线程更新UI,不要在UI线程进行耗时操作。偶然间的尝试发现了一些奇怪的问题,先分析第一个问题子线程中可以更新UI吗?下面是我的代码:

Android设置全屏及沉浸式布局

下述代码根据 AppCompatActivity 及主题 parent="Theme.AppCompat.NoActionBar"midSdk 21实现。

对于非刘海屏幕而言有两种方式设置全屏

  1. 代码中设定,需要写在 setContentView() 之前:

    1
    2
    3
    4
    5
    6
    // 隐藏标题
    //requestWindowFeature(Window.FEATURE_NO_TITLE);
    // 设置全屏
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
    //或者是通过设置DecorView#setSystemUiVisibility(int)
    //getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN)

    需要说明一点 requestWindowFeature() 方法是指定主题为 parent="android:Theme.Black"之类的Activity 时隐藏老式 ActionBar 标题栏内容。对于继承 AppCompatActivity 这个方法无效。如果继承 AppCompatActivity 的 Activity 需要隐藏标题栏,可以通过以下方法:

Android okhttp使用详解

Get 请求

1
2
3
4
5
6
7
Request request = new Request.Builder()
.url(url)
.build();
OkHttpClient client = new OkHttpClient();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}

通过Request构建请求体,然后由 client 执行。这里 Request 默认请求类型是Get。注意这个是SynchronousGet是同步执行的。在Android UI线程直接运行会报错提示:==android.os.NetworkOnMainThreadException==。

Android使用RenderScript处理图片

RenderScriptAndroid平台上简单快速处理图片效果的脚本工具,Renderscript``基于C99(Ed. C 语言)。使用前需要在Modulebuild.gradle文件中添加两行代码:

1
2
3
4
5
defaultConfig {
//略...
renderscriptTargetApi 24
renderscriptSupportModeEnabled true
}

Android预览pdf文档

谷歌为我们提供了PdfRender工具类对pdf文档进行渲染,首先看一下PdfRender的构造方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Creates a new instance.
* <p>
* <strong>Note:</strong> The provided file descriptor must be <strong>seekable</strong>,
* i.e. its data being randomly accessed, e.g. pointing to a file.
* </p>
* <p>
* <strong>Note:</strong> This class takes ownership of the passed in file descriptor
* and is responsible for closing it when the renderer is closed.
* </p>
* <p>
* If the file is from an untrusted source it is recommended to run the renderer in a separate,
* isolated process with minimal permissions to limit the impact of security exploits.
* </p>
*
* @param input Seekable file descriptor to read from.
*
* @throws java.io.IOException If an error occurs while reading the file.
* @throws java.lang.SecurityException If the file requires a password or
* the security scheme is not supported.
*/
public PdfRenderer(@NonNull ParcelFileDescriptor input){
//略...
}

可以看构造方法中的参数是ParcelFileDescriptor的一个实例,那么ParcelFileDescriptor类是做什么的呢?ParcelFileDescriptor是Android 提供的一种数据结构,支持数据的写入和写出。我们通过ParcelFileDescriptor#open 建立文件和ParcelFileDescriptor的联系

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×