欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android 开发你需要了解的那些事

程序员文章站 2023-10-18 23:57:40
本文微信公众号「AndroidTraveler」首发。 背景 最近部门有新入职员工,作为规划技术路线的导师,这边给新员工安排了学习路线。 除了基本的学习路线之外,每次沟通,我都留了一个小问题,让小伙伴去思考。 这些问题有些是刚接触 Android 开发的小伙伴所不熟悉的,有些则是部分初级工程师都没有 ......

本文微信公众号「androidtraveler」首发。

背景

最近部门有新入职员工,作为规划技术路线的导师,这边给新员工安排了学习路线。

除了基本的学习路线之外,每次沟通,我都留了一个小问题,让小伙伴去思考。

这些问题有些是刚接触 android 开发的小伙伴所不熟悉的,有些则是部分初级工程师都没有注意到的。

因此这边纪录一下,希望帮助刚毕业进入职场的 android 小伙伴,或是对这些还不是很熟悉的 android 开发工程师们。

如有补充或者交流,欢迎留言。

第一点:anr 的其中一个条件并不是在 activity 主线程做耗时任务

q: 你是否了解过 anr?
a: 知道,但不是很了解。

q: 什么情况下会出现 anr?
假设这里回答的不是“在主线程执行耗时任务”的话,可以不继续追问,直接让小伙伴去了解 anr,后期再讨论。
如果回答了是“在主线程执行耗时任务”的话,那么继续:

q: 多久算耗时?
a: 不要超过 5s。

q: 那么假设我在 activity sleep 20s,是不是就一定会 anr?

上代码例子:
mainactivity.java 文件:

public class mainactivity extends appcompatactivity {

    @override
    protected void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        setcontentview(r.layout.activity_main);
        findviewbyid(r.id.button).setonclicklistener(new view.onclicklistener() {
            @override
            public void onclick(view view) {
                log.e("zengyu","before sleep");
                try {
                    thread.sleep(20000);
                } catch (interruptedexception e) {
                    e.printstacktrace();
                }
                log.e("zengyu","after sleep");
            }
        });
    }

}

activity_main.xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.constraintlayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".mainactivity">

    <button
        android:id="@+id/button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margintop="8dp"
        android:text="button"
        app:layout_constraintend_toendof="parent"
        app:layout_constraintstart_tostartof="parent"
        app:layout_constrainttop_totopof="parent" />

</android.support.constraint.constraintlayout>

代码功能很简单,就是一个按钮,点击之后会 sleep 20 秒。在 sleep 前和 sleep 后都会打印日志。

如果你只是点击按钮,然后什么都不动,是不会有 anr 的。

但是你点击了按钮之后,你继续多次点击按钮,那么就会有 anr 了。

以下四个条件都可以造成anr发生:
inputdispatching timeout: 5秒内无法响应屏幕触摸事件或键盘输入事件
broadcastqueue timeout : 在执行前台广播(broadcastreceiver)的onreceive()函数时10秒没有处理完成,后台为60秒。
service timeout : 前台服务20秒内,后台服务在200秒内没有执行完毕。
contentprovider timeout : contentprovider的publish在10s内没进行完。

所以可能很多小伙伴会把上面四个条件的第一个和 activity 直接挂钩,以为是在主线程耗时超过 5s 就会 anr。实际上是 inputdispatching。

第二点:子线程使用

q: 既然主线程不能做耗时任务,那么有耗时任务怎么办?

a: 通过 new thread 启动一个子线程,在子线程处理。

q: 考虑一个场景,比如类似微信这类 im 软件收到消息。需要写数据库,这个时候需要启动线程。当收到消息 n 多的时候,如果都用 new thread 启动线程的话,是否会有问题。场景模拟可以通过循环创建子线程模拟。

上代码例子:
mainactivity.java 文件:

public class mainactivity extends appcompatactivity {
    @override
    protected void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        setcontentview(r.layout.activity_main);
        for (int i = 0; i < 10000; i++) {
            new thread(new runnable() {
                @override
                public void run() {
                    try {
                        thread.sleep(5000);
                    } catch (interruptedexception e) {
                        e.printstacktrace();
                    }
                }
            }).start();
        }
    }
}

这个部分手机厂商比如(华为)有对线程数目做限制的话,一运行就会 crash,logcat 会看到下面信息:

pthread_create (1040kb stack) failed: out of memory

我这边一开始在三星 s7 上面运行,并没有出现。后面换成华为 5x 手机就出现了。

android 开发的小伙伴都知道兼容是硬伤,所以我们不能抱有侥幸心理。

针对这种情况,我们不能一遇到耗时任务,就很潇洒的一个 new thread 全部搞定。

如果你当前界面只有一个耗时任务,而且只需要调用一次,那么你进入该界面用 new thread 来处理没有问题。

但是假设像上面我们描述的场景那样,需要调用多次的时候。你就不能简单粗暴的使用 new thread 了。

推荐方式是使用线程池。
一个原因是避免一些厂商的线程数目限制。
另一个原因是减少线程的频繁创建和销毁。

第三点:内部类都可能存在的问题

q: 上面我们说到了,如果界面调用一次,而且需要启动线程的时候。可以使用 new thread 创建,那么直接使用 new thread 可能还有什么问题吗?

这里想考察的点可能比较晦涩一点。

由于内部类会持有外部类的引用。假设在 activity 里面通过匿名内部类的方式来启动线程做耗时任务。当用户退出界面时,由于内部类还持有 activity 的引用,因此 activity 没法得到释放。

就会存在内存泄漏问题。

解决方法也比较统一,那就是将内部类改为静态内部类。

所以修改后的代码对比如下:

修改前:

public class mainactivity extends appcompatactivity {
    @override
    protected void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        setcontentview(r.layout.activity_main);
        new thread(new runnable() {
            @override
            public void run() {
                //todo
            }
        }).start();
    }
}

修改后:

public class mainactivity extends appcompatactivity {
    @override
    protected void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        setcontentview(r.layout.activity_main);
        new staticthread().start();
    }

    private static class staticthread extends thread {
        @override
        public void run() {
            super.run();
            //todo
        }
    }
}

第四点:弱引用场景应用

q: 用过 handler 吗?

a: 用过。

q: 写一下简单的 demo 我看下。

这个是紧接第三点。如果不涉及界面交互,只需要使用到静态内部类就可以解决。但是当 handler 里面需要做界面更新处理时,那么需要使用弱引用。因为静态内部类的处理方式本来就是为了避免 activity 无法得到释放。你如果把 activity 直接传进来,那么 activity 的引用被静态内部类持用了,所以这个时候就需要使用到弱引用了。

直接上代码:

public class mainactivity extends appcompatactivity {
    private static class statichandler extends handler {
        private weakreference<mainactivity> activityweakreference;

        public statichandler(mainactivity mainactivity) {
            this.activityweakreference = new weakreference<>(mainactivity);
        }

        @override
        public void handlemessage(message msg) {
            super.handlemessage(msg);
            //todo
            //use activityweakreference.get() to get view
        }
    }

    private statichandler mstatichandler = new statichandler(this);
    @override
    protected void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        setcontentview(r.layout.activity_main);
        mstatichandler.sendemptymessage(0);
    }
}

第五点:持久化 sharedpreferences 的使用

一般很多网上教程和例子在 sharedpreferences 的数据写入时,一般都会使用 editor 的 commit 方法。

由于 commit 方法是同步写入的。并且写文件属于 i/o 操作,如果你有大量的数据需要写入,并且你是在主线程处理的,可能会导致流畅性受影响。极端情况下可能会出现 anr。

我们点进去源码看下:

if you don't care about the return value and you're using this from your application's main thread, consider using {@link #apply} instead.

其实源码也说的很清楚了。如果你不关心返回值并且你是在应用的主线程使用的话,考虑使用 apply 替换 commit。

由于我们一般不会处理返回值,因此建议使用 apply 替换 commit。

apply 会把变化马上写进内存,然后通过异步方式去写入。

unlike {@link #commit}, which writes its preferences out to persistent storage synchronously, {@link #apply} commits its changes to the in-memory {@link sharedpreferences} immediately but starts an asynchronous commit to disk and you won't be notified of any failures.

当然源码还有一个注释如下:

if another editor on this {@link sharedpreferences} does a regular {@link #commit} while a {@link #apply} is still outstanding, the {@link #commit} will block until all async commits are completed as well as the commit itself.

大概意思就是 apply 如果在处理中还未完成的情况下,commit 会阻塞直到所有异步操作完成才会去 commit。

因此如果要替换,建议将 commit 都替换为 apply。

第六点:数据库相关处理

这里主要是考虑类似微信 im 登录后拉取大量离线消息写入数据库的问题。

通过对比开启事务和不开启事务的耗时来进行说明。

比如不开启事务插入 10000 条纪录和开启事务插入 10000 条纪录耗时对比。

对于大量的数据库操作,建议开启事务的方式,速度的提升是很明显的。

参考链接:
android anr:原理分析及解决办法

Android 开发你需要了解的那些事