Home >Web Front-end >Front-end Q&A >Analysis of Android advanced interview questions and answers
Recommended: "2020 Android Interview Questions Summary [Collection]"
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.
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.
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
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)); }
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 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.
I.ArrayMap/SparseArray instead of hashmap
II. Avoid using Enum
in androidIII. Reduce the memory usage of bitmap
IV. Reduce the size of resource images. For images that are too large, consider loading them in sections
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
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); } }
CrashHandler
The key is to implement Thread.UncaughtExceptionHandler
and then register it in oncreate of the application.
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
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发生的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
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的使用量
从log可以看出,cpu在做大量的io操作。
所以可以查看io操作的地方。
当然,也有可能cpu占用不高,那就是 主线程被block住了。
1)共享变量(内存)
2)管道
3)handle机制
runOnUiThread(Runnable)
view.post(Runnable)
Dalvik进程。
每一个android app都会独立占用一个dvm虚拟机,运行在linux系统中。
所以dalvik进程和linux进程是可以理解为一个概念。
从小到上就是:
linux kernel,lib dalvik vm ,application framework, app
activitymanager.getMemoryClass() 获取内存限制。
关于合理使用内存,其实就是避免OOM & 内存泄露中已经说明。
1)main code
2) unit test
3)mianifest
4)res->drawable,drawable-xxhdpi,layout,value,mipmap
mipmap 是一种很早就有的技术了,翻译过来就是纹理映射技术.
google建议只把启动图片放入。
5)lib
6)color
文件的系统权限是由linux系统规定的,只读,读写等。
运行时权限,是对于某个系统上的app的访问权限,允许,拒绝,询问。该功能可以防止非法的程序访问敏感的信息。
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中的布局加载进来。
线程间的通信可以参考第6点。
进程间的通信:bind机制(IPC->AIDL),linux级共享内存,boradcast,
Activity 之间,activity & serview之间的通信,无论他们是否在一个进程内。
屏幕适配的方式:xxxdpi, wrap_content,match_parent. 获取屏幕大小,做处理。
dp来适配屏幕,sp来确定字体大小
drawable-xxdpi, values-1280*1920等 这些就是资源的适配。
wrap_content,match_parent, 这些是view的自适应
weight,这是权重的适配。
Android Interface Definition Language
AIDL是使用bind机制来工作。
参数:
java原生参数
String
parcelable
list & map 元素 需要支持AIDL
参考:android 进程/线程管理(一)----消息机制的框架 这个系类。
android 事件分发机制
EventBus,广播,view.post, runinUiThread
但是无论各种花样,本质上就2种:handler机制 + 广播
必须可以。子线程 可以new 一个mainHandler,然后发送消息到UI Thread。
视图动画,或者说补间动画。只是视觉上的一个效果,实际view属性没有变化,性能好,但是支持方式少。
属性动画,通过变化属性来达到动画的效果,性能略差,支持点击等事件。android 3.0
帧动画,通过drawable一帧帧画出来。
Gif动画,原理同上,canvas画出来。
具体可参考:https://i.cnblogs.com/posts?categoryid=672052
overridePendingTransition
view的更新必须在UI thread中进行
surfaceview会单独有一个线程做ui的更新。
surfaceview 支持open GL绘制。
I.EventBus 事件分发机制,由handler实现,线程间通信
II.xUtils->DbUtils,ViewUtils,HttpUtils,BitmapUtils
III.百度地图
IV.volley
V.fastjson
VI.picciso
VII.友盟
VIII.zxing
IX.Gson
pull2RefreshListView
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); } }
CycleView
关键是canvas.drawCycle & paint.setsytle(stoken)
可以不需要adapter
TBD.
QQ & 微信都有第三方登陆的sdk,要去注册app
需要看支付宝的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!