Analysis of Android advanced interview questions and answers

藏色散人
Release: 2020-07-31 17:07:38
forward
4669 people have browsed it

Recommended: "2020 Android Interview Questions Summary [Collection]"

1. Performance Optimization

1. How to optimize Android Application performance analysis

android performance mainly depends on response speed and UI refresh speed.

You can refer to the blog: Introduction to Android System Performance Tuning Tools

First of all, in terms of function time-consuming, there is a tool TraceView, which is the work that comes with androidsdk, used to measure function time-consuming of.

The analysis of UI layout can have two parts. One is the Hierarchy Viewer. You can see the layout level of the View and the refresh and load time of each View.

This way you can quickly locate the layout & view that takes the longest.

Another option is to reduce the level of views by customizing Views.

2. Under what circumstances will memory leaks occur?

Memory leaks are a difficult problem.

When does a memory leak occur? The root cause of memory leaks: long-lived objects holding short-lived objects. Short-lived objects cannot be released in time.

I. Static collection classes cause memory leaks

Mainly is hashmap, Vector, etc. If these collections are static collections, these objects will always be held if null is not set in time.

II.remove method cannot delete the set Objects.hash(firstName, lastName);

After testing, after the hashcode is modified, there is no way to remove.

III. observer When we use listeners, we often addxxxlistener, but when we don’t need it, if we forget to removexxxlistener, it is easy for the memory to leak.

Broadcasting does not unregisterrecevier

IV. Various data links are not closed, database contentprovider, io, sokect, etc. cursor

V. Internal class:

The internal class (anonymous internal class) in Java will hold the strong reference this of the host class.

So if it is a background thread operation such as new Thread, when the thread does not end, the activity will not be recycled.

Context reference, TextView, etc. will hold the context reference. If there is a static drawable, the memory will not be released.

VI. Singleton

The singleton is a global static object. When a copied class A is held, A cannot be released and the memory leaks.

3. How to avoid OOM exceptions

First of all, what is OOM?

When the program needs to apply for a "large" memory, but the virtual machine cannot provide it in time, even after performing a GC operation

This will throw an OutOfMemoryException, which is OOM

How about Android’s OOM?

In order to reduce the impact of a single APP on the entire system, Android sets a memory limit for each 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));
    }
Copy after login
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
Copy after login

HTC M7 actual measurement, 192M upper limit. 512M Under normal circumstances, 192M is the upper limit, but due to some special circumstances, Android allows the use of a larger RAM.

How to avoid OOM

Reduce memory object usage

I.ArrayMap/SparseArray instead of hashmap

II. Avoid using Enum

in android

III. Reduce the memory usage of bitmap

  • inSampleSize: scaling ratio. Before loading the image into the memory, we need to calculate an appropriate scaling ratio to avoid unnecessary loading of large images. enter.
  • decode format: Decoding format, select ARGB_8888/RBG_565/ARGB_4444/ALPHA_8, there are big differences.

IV. Reduce the size of resource images. For images that are too large, consider loading them in sections

Reuse of memory objects

Reuse of most objects. They all use object pool technology.

I.listview/gridview/recycleview contentview reuse

II.inBitmap attribute reuse of memory objects ARGB_8888/RBG_565/ARGB_4444/ALPHA_8

This method is used in a certain It is very useful under certain conditions, such as when thousands of images are to be loaded.

III. Avoid new objects in the ondraw method

IV.StringBuilder instead

4.How to catch uncaught exceptions in 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);
    }
}
Copy after login

CrashHandler

The key is to implement Thread.UncaughtExceptionHandler

and then register it in oncreate of the application.

5.What is ANR? How to avoid and solve ANR (important)

ANR->Application Not Responding

That is, there is no response within the specified time.

Three types:

1). KeyDispatchTimeout(5 seconds) --The main type of key or touch event does not respond within a specific time

2). BroadcastTimeout(10 seconds) --BroadcastReceiver cannot be processed within a specific time

3). ServiceTimeout(20 seconds) --There is a small probability that the service cannot be processed within a specific time

Why it times out: Events have no chance to be processed & event processing timeout

How to avoid ANR

The key to ANR

is the processing timeout, so it should be avoided in the UI thread, BroadcastReceiver and service main thread , handle complex logic and calculation

and leave it to the work thread for operation.

1) Avoid doing time-consuming operations in the activity, oncreate & onresume

2) Avoid doing too many operations in onReceiver

3) Avoid starting in Intent Receiver An Activity because it creates a new screen and steals focus from the program currently running by the user.

4)尽量使用handler来处理UI thread & workthread的交互。

如何解决ANR

首先定位ANR发生的log:

04-01 13:12:11.572 I/InputDispatcher( 220): Application is not responding:Window{2b263310com.android.email/com.android.email.activity.SplitScreenActivitypaused=false}.  5009.8ms since event, 5009.5ms since waitstarted
Copy after login
CPUusage from 4361ms to 699ms ago ----CPU在ANR发生前的使用情况04-0113:12:15.872 E/ActivityManager(  220): 100%TOTAL: 4.8% user + 7.6% kernel + 87% iowait04-0113:12:15.872 E/ActivityManager(  220): CPUusage from 3697ms to 4223ms later:-- ANR后CPU的使用量
Copy after login

从log可以看出,cpu在做大量的io操作。

所以可以查看io操作的地方。

当然,也有可能cpu占用不高,那就是 主线程被block住了。

6.Android 线程间通信有哪几种方式

1)共享变量(内存)

2)管道

3)handle机制

runOnUiThread(Runnable)

view.post(Runnable)

7.Devik 进程,linux 进程,线程的区别

Dalvik进程。

每一个android app都会独立占用一个dvm虚拟机,运行在linux系统中。

所以dalvik进程和linux进程是可以理解为一个概念。

8.描述一下 android 的系统架构

从小到上就是:

linux kernel,lib dalvik vm ,application framework, app

9.android 应用对内存是如何限制的?我们应该如何合理使用内存?

activitymanager.getMemoryClass() 获取内存限制。

关于合理使用内存,其实就是避免OOM & 内存泄露中已经说明。

10. 简述 android 应用程序结构是哪些

1)main code

2) unit test

3)mianifest

4)res->drawable,drawable-xxhdpi,layout,value,mipmap

mipmap 是一种很早就有的技术了,翻译过来就是纹理映射技术.

google建议只把启动图片放入。

5)lib

6)color

11.请解释下 Android 程序运行时权限与文件系统权限的区别

文件的系统权限是由linux系统规定的,只读,读写等。

运行时权限,是对于某个系统上的app的访问权限,允许,拒绝,询问。该功能可以防止非法的程序访问敏感的信息。

12.Framework 工作方式及原理,Activity 是如何生成一个 view 的,机制是什么

Framework是android 系统对 linux kernel,lib库等封装,提供WMS,AMS,bind机制,handler-message机制等方式,供app使用。

简单来说framework就是提供app生存的环境。

1)Activity在attch方法的时候,会创建一个phonewindow(window的子类)

2)onCreate中的setContentView方法,会创建DecorView

3)DecorView 的addview方法,会把layout中的布局加载进来。

13.多线程间通信和多进程之间通信有什么不同,分别怎么实现

线程间的通信可以参考第6点。

进程间的通信:bind机制(IPC->AIDL),linux级共享内存,boradcast,

Activity 之间,activity & serview之间的通信,无论他们是否在一个进程内。

14.Android 屏幕适配

屏幕适配的方式:xxxdpi, wrap_content,match_parent. 获取屏幕大小,做处理。

dp来适配屏幕,sp来确定字体大小

drawable-xxdpi, values-1280*1920等 这些就是资源的适配。

wrap_content,match_parent, 这些是view的自适应

weight,这是权重的适配。

15.什么是 AIDL 以及如何使用

Android Interface Definition Language

AIDL是使用bind机制来工作。

参数:

java原生参数

String

parcelable

list & map 元素 需要支持AIDL

16.Handler 机制

参考:android 进程/线程管理(一)----消息机制的框架 这个系类。

17.事件分发机制

android 事件分发机制

18.子线程发消息到主线程进行更新 UI,除了 handler 和 AsyncTask,还有什么

EventBus,广播,view.post, runinUiThread

但是无论各种花样,本质上就2种:handler机制 + 广播

19.子线程中能不能 new handler?为什么

必须可以。子线程 可以new 一个mainHandler,然后发送消息到UI Thread。

20.Android 中的动画有哪几类,它们的特点和区别是什么

视图动画,或者说补间动画。只是视觉上的一个效果,实际view属性没有变化,性能好,但是支持方式少。

属性动画,通过变化属性来达到动画的效果,性能略差,支持点击等事件。android 3.0

帧动画,通过drawable一帧帧画出来。

Gif动画,原理同上,canvas画出来。

具体可参考:https://i.cnblogs.com/posts?categoryid=672052

21.如何修改 Activity 进入和退出动画

overridePendingTransition

22.SurfaceView & View 的区别

view的更新必须在UI thread中进行

surfaceview会单独有一个线程做ui的更新。

surfaceview 支持open GL绘制。

二、项目框架的使用

23.开发中都使用过哪些框架、平台

I.EventBus 事件分发机制,由handler实现,线程间通信

II.xUtils->DbUtils,ViewUtils,HttpUtils,BitmapUtils

III.百度地图

IV.volley

V.fastjson

VI.picciso

VII.友盟

VIII.zxing

IX.Gson

24.使用过那些自定义View

pull2RefreshListView

25.自定义控件:绘制圆环的实现过程

package com.joyfulmath.samples.Cycle;import android.content.Context;import android.graphics.Canvas;import android.graphics.Paint;import android.util.AttributeSet;import android.view.View;/**
 * Created by Administrator on 2016/9/11 0011. */public class CycleView extends View {
    Paint mPaint = new Paint();    public CycleView(Context context) {        this(context, null);
    }    public CycleView(Context context, AttributeSet attrs) {        super(context, attrs);
        initView();
    }    private void initView() {
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(20);
    }

    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);
        canvas.drawCircle(100,100,50,mPaint);
    }
}
Copy after login

CycleView

关键是canvas.drawCycle & paint.setsytle(stoken)

26.自定义控件:摩天轮的实现过程

27.GridLayout的使用

可以不需要adapter

28.流式布局的实现过程

TBD.

29.第三方登陆

QQ & 微信都有第三方登陆的sdk,要去注册app

30.第三方支付

需要看支付宝的API文档

The above is the detailed content of Analysis of Android advanced interview questions and answers. For more information, please follow other related articles on the PHP Chinese website!

source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template