2024Android-高级面试题及答案(Google收录,值得推荐!)

VI.单例

单例 是一个全局的静态对象,当持有某个复制的类A是,A无法被释放,内存leak。

回到顶部

3.如何避免 OOM 异常

首先OOM是什么?

当程序需要申请一段“大”内存,但是虚拟机没有办法及时的给到,即使做了GC操作以后

这就会抛出 OutOfMemoryException 也就是OOM

Android的OOM怎么样?

为了减少单个APP对整个系统的影响,android为每个app设置了一个内存上限。

public void getMemoryLimited(Activity context)
{
ActivityManager activityManager =(ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
System.out.println(activityManager.getMemoryClass());
System.out.println(activityManager.getLargeMemoryClass());
System.out.println(Runtime.getRuntime().maxMemory()/(1024*1024));
}

09-10 10:20:00.477 4153-4153/com.joyfulmath.samples I/System.out: 192
09-10 10:20:00.477 4153-4153/com.joyfulmath.samples I/System.out: 512
09-10 10:20:00.477 4153-4153/com.joyfulmath.samples I/System.out: 192

HTC M7实测,192M上限。512M 一般情况下,192M就是上限,但是由于某些特殊情况,android允许使用一个更大的RAM。

如何避免OOM
减少内存对象的占用

I.ArrayMap/SparseArray代替hashmap

II.避免在android里面使用Enum

III.减少bitmap的内存占用

  • inSampleSize:缩放比例,在把图片载入内存之前,我们需要先计算出一个合适的缩放比例,避免不必要的大图载入。
  • decode format:解码格式,选择ARGB_8888/RBG_565/ARGB_4444/ALPHA_8,存在很大差异。

IV.减少资源图片的大小,过大的图片可以考虑分段加载

内存对象的重复利用

大多数对象的复用,都是利用对象池的技术。

I.listview/gridview/recycleview contentview的复用

II.inBitmap 属性对于内存对象的复用ARGB_8888/RBG_565/ARGB_4444/ALPHA_8

这个方法在某些条件下非常有用,比如要加载上千张图片的时候。

III.避免在ondraw方法里面 new对象

IV.StringBuilder 代替+

回到顶部

4.Android 中如何捕获未捕获的异常

public class CrashHandler implements Thread.UncaughtExceptionHandler {

private static CrashHandler instance = null;

public static synchronized CrashHandler getInstance()
{
if(instance == null)
{
instance = new CrashHandler();
}
return instance;
}

public void init(Context context)
{
Thread.setDefaultUncaughtExceptionHandler(this);
}

@Override
public void uncaughtException(Thread thread, Throwable ex) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(“Thread:”);
stringBuilder.append(thread.toString());
stringBuilder.append(“\t”);
stringBuilder.append(ex);
TraceLog.i(stringBuilder.toString());
TraceLog.printCallStatck(ex);
}
}

关键是实现Thread.UncaughtExceptionHandler

然后是在application的oncreate里面注册。

回到顶部

5.ANR 是什么?怎样避免和解决 ANR(重要)

ANR->Application Not Responding

也就是在规定的时间内,没有响应。

三种类型:

1). KeyDispatchTimeout(5 seconds) --主要类型按键或触摸事件在特定时间内无响应

2). BroadcastTimeout(10 seconds) --BroadcastReceiver在特定时间内无法处理完成

3). ServiceTimeout(20 seconds) --小概率类型 Service在特定的时间内无法处理完成

为什么会超时:事件没有机会处理 &am

你可能感兴趣的:(android)