安卓开发安卓开发安卓集中营

安卓常见crash问题及防护措施

2019-11-12  本文已影响0人  蓝不蓝编程

1. 使用对象属性前需要判断对象是否为null

name = user.name;
nameLength = user.name.length();
if(user != null)
{
    name = user.name;
    if(user.name != null)
    {
        nameLength = user.name.length();
    }
}

2. 访问数组及列表时,需要判断下标是否超出范围

String element = arr[index];
int index = 0;
if (arr != null && index >= 0 && index < arr.length) {
    String element = arr[index];
}

3. 类型强制转化时,需要对类型进行检查

Student stu = (Student) people;
if(people instanceof Student)
{
    Student stu = (Student) people;
}

4. 异步任务回调更新ui或调用activity方法时需要判断activity状态

mActivity.xx();
if (!(mActivity.isFinishing() || Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mActivity.isDestroyed())) {
    mActivity.xx();
}

5. 显示dialog前需要对所属activity状态做判断

dialog.show();
Dialog dialog = new Dialog(this);
if (!(mActivity.isFinishing() || Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mActivity.isDestroyed())
        && dialog != null
        && dialog.isShowing()) {
    dialog.show();
}

6. 避免不必要的activity依赖

对于Toast和SharedPreference,都不需要依赖activity.

Toast.makeText(getActivity(), "出错啦", Toast.LENGTH_SHORT).show();
Toast.makeText(applicationContext, "出错啦", Toast.LENGTH_SHORT).show();
上一篇 下一篇

猜你喜欢

热点阅读