Asked in an interview before the database network request .IntentService. View draw. Memory leak .OOM. Animation Framework Custom view.Glide source attribute animated series of problems, and so, although all answer it, but still there are some details of things did not get attention.
Come back after finishing a lot of knowledge became a PDF, it is quite comprehensive
( ^ ▽ ^ )
from basic to advanced. Contains BATJ. Byte beating interview topics, topics algorithms, high-end technology topics, mixed-use development themes, java interview topics, Android, Java little knowledge, to performance optimization. Threads .View.OpenCV.NDK everything. There supplemented by related video + study notes
(.... To be continued more complete project source code download graphic knowledge subsequent upload github)
can click on my contact me for a full PDF
( VX: mm14525201314 )
1. Database of the type of operation which, how to import external databases?
Read the title. If you have problems rather vague when you can properly ask the interviewer.
With the interviewer to interview : The interview is a process of mutual understanding, to make full use of the title and time of the interview to their ability and technology to show up, the interviewer can see your true technology.
1) use of the database options?
openOrCreateDatabase(String path);
- Inherited
SqliteOpenHelper
class version of its database management (onCreate
,onUpgrade
)
when calling methods of this class in the program amonggetWritableDatabase()
orgetReadableDatabase();
time will open the database. There was no time if the database file, the system will automatically generate a database.
2) Type of operation: CRUD CRUD
Direct SQL statements : SQliteDatabase.execSQL(sql);
for operation objects :SQLiteDatabase.insert(table, nullColumnHack, ContentValues);
How to import external databases?
General external database files on the SD card may or res / raw directory or assets.
Write a DBManager
class to manage, move the database files, first copy the database file to "/ data / data / package name / databases /" directory, then db.openOrCreateDatabase(db文件)
open the database to use.
I did just that on a project, due to the need to have some initial data before the built-in app shelves, will encounter upgrade data and other issues, what I did ...... at the same time I met the most interesting question is about the database concurrency operational issues, such as: multi-threaded operation of the database, I take that package to use a mutex to solve ......
2. Whether used local radio, and global broadcast what is the difference?
The introduction of local broadcast mechanism is to address security issues:
1) broadcast being transmitted without departing from the application, than worry about data leakage app's;
2) other programs can not be sent to the interior of my application, do not worry about security vulnerabilities. (For example: how to make a kill service --- monitor the fire app such as micro-letters, Friends of the Union, Aurora broadcast, to start their own.)
3) send local broadcast than the broadcast sent global efficiency. (Lower to maintain the global broadcast of the broadcast table collection efficiency global broadcast, means that you can cross-process, you need the support of the ground floor.)
Local broadcasting can not use static registration . ---- static registration: can be done to stop the program can monitor.
use:
- Registration:
LocalBroadcastManager.getInstance(this).registerReceiver(new XXXBroadCastReceiver()
,new IntentFilter(action));
- Unregister:
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver)
3. Whether used IntentService, what role is, AIDL solve the problem?
If a task can be divided into many sub-tasks required to complete the order, if you need into one service is completed, then the use IntentService
is the best choice.
General Service we use are among the main thread, so time-consuming operation code written in the service inside, the card will be the main thread ANR
. To solve this problem, Google introduced IntentService
.
IntentService
Advantages:
(1) it creates a separate thread to handle all the work one by one intent.
(2) creates a work queue to sending individual intent to onHandleIntent()
(3) do not need to take the initiative to call stopSelf()
for the end of the service, because the source code inside their own to achieve the automatic shut down.
(4) default implementation onBind()
null is returned.
(5) The default implementation onStartCommand()
object intent is to insert into the queue.
Summary: Use IntentService
the benefits of what. First, eliminating the hassle of manually open thread; second, without having to manually stop the service; third, because of the design of the job queue, you can start several times --- startService()
but only instance of a service and a worker thread. A familiar anger execution.
AIDL solve the problem?
AIDL full name: Android Interface Definition Language, Android Interface Definition Language.
Since Android does not share memory between processes in the system, so it is necessary to provide some mechanism for data communication between different processes.
Remote Procedure Call: RPC-Remote Procedure Call. Andrews is to provide a IDL
solution to open their own service interface. AIDL: can be understood as two sides of a contractual agreement. The two sides should hold the text of the agreement --- protocol xxx.aidl
file (internal Andrews compile time will be aidl
protocol translation xxx.java file --- generate a proxy mode:. Binder driver-related, Linux underlying communication-related)
in the system there are a lot of source used aidl, such as a system service.
TV set-top box system development. Your service to be exposed to other developers to use.
Binder explain the mechanism.
4.Activity, Window, three different View, fragment characteristics?
Activity, Window, View how the three interactive display interface. --- test sites: process (view drawing process) displays the source code of familiarity.
Activity shear bars persons (control); the Window window (carried by a model); grilles View (View to display the view); LayoutInflater
scissors --- layout (drawing) cut grilles.
(Alt + direction of the arrow)
fragment of features? (You have no taste fragment with some fun, or have not stepped on any pit?)
fragment designed primarily including logic to interface Activity broken up into a number of separate modules, it is easy to reuse modules and assembled more flexibly presented various interface.
- Fragment Activity may be composed as a part of the interface;
- It may occur in a plurality of Fragment Activity inside, and a plurality of fragment can be used in an Activity;
- Activity in operation, can dynamically add, delete, replace Fragment.
- Fragment has its own life cycle, you can respond to input events.
Stepped pit:
- overlapping;
- Notes
newAPI
(Compatibility Pack resolved); Setarguement()
Initialization data;- Can not
onsave
after ... () method, commit; - Push pop issues; - affairs. Activity like before jumping the same effect, but also time and returns back to the page (fragment) and the state are still. replace (f1, f2) seriously affect the life cycle: add () + show + hide
The lower version of the SDK version for high api
Several situations:
1) is generally much higher versions of the new API will find alternative implementations compatible package inside. For example fragment.
Notification, v4 compatible package inside theNotificationCompat
class. 5.0+ appearsbackgroundTint
,minSdk
if less than 5.0 would detect an error packet, v4 compatible packageDrawableCompat
classes.
2) there is no alternative to achieve on their own to achieve manually. For example: water ripple effect controls - third-party implementations.
Or remove this effect directly in the low version.
3) NOTE: If you set upminSDK
but the code which uses a high version of the API, detect errors. Need to use the statement in the code inside compilers detection strategy, such as:@SuppressLint
and@TargetApi
annotate the presentation rule compiler.@SuppressLint
Detection is ignored;@TargetApi=23
will you inside according to API functions used strictly match theSDK
version given by the appropriate compiler error.
4) In order to avoid the wrong position, it is best not to use waste api. (Under normal circumstances there will be no compatibility problems might be back at any time to delete this API method; performance problems.)
6. launch mode scenario
Stack : advanced after
Standard ModeSingleTop
: Use Scene: browser bookmarks; communication message chat interface. SingleTask
: Usage scenarios: an Activity as the main interface of the time. SingleInstance
: Usage scenarios: for example, the browser BrowserActivity
is consuming memory, many app will want to call it, so that you can set the Activity Singleton pattern. For example: alarm clock alarm.
7.view drawing process
Measure: Measure, measure yourself. If ViewGroup
you need to measure all inside childview
.
The results of measuring how do? setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState), heightSizeAndState);
Set your own size.
Layout: place, put himself in the position which. If ViewGroup
you need to release all inside childview
.
How to specifically put it?
Draw : Draw
/*
* Draw traversal performs several drawing steps which must be executed
* in the appropriate order:
*
* 1. Draw the background
* 2. If necessary, save the canvas' layers to prepare for fading
* 3. Draw view's content
* 4. Draw children
* 5. If necessary, draw the fading edges and restore layers
* 6. Draw decorations (scrollbars for instance)
*/
8. What causes a memory leak
1) What is a memory leak: best explain GC garbage collection mechanism and the concept of GC Root.
2) Why is there a memory leak: Because the Memory leaks are caused by human error belongs. And the relationship between object-oriented development complex, multi-threaded relationship, it is prone to quote a deep hierarchy and very confusing.
3) What is the situation likely to cause a memory leak:
4) How to troubleshoot memory leaks
9. ANR positioning and correction
ANR can be viewed by looking /data/anr/traces.txt.
The fundamental reason is : the main thread was stuck, causing the application in 5 seconds did not respond to user input events.
A variety of scenarios ANR error occurred:
- Implementation of IO / network operations among the main thread, easily blocked.
- Among the main thread to perform time-consuming calculation. ---- custom control when onDraw method which often do.
(Chat while performance custom control Optimization:onDraw
Creating objects inside easily lead to memory churn --- draw a lot of action will continue to call, resulting in a large amount of garbage objects GC is very frequent and causing memory jitter) are likely to cause jitter memory UI problem dropped frames Caton BroadCastReceiver
Processing is not completed within 10 seconds.BroadCastReceiver
TheonReceived
code should minimize time-consuming operation, recommendedIntentService
treatment.- Service to perform time-consuming operation because the service is performed in which the main thread, so time-consuming operations should be opened in the child thread to do the service inside.
- Use
AsyncTask
time consuming process IO operations. - Thread use or
HandlerThread
when to useProcess.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND)
orjava.lang.Thread.setPriority (int priority)
set the priority for the background priority, which would allow other multi-threaded CPU-time is reduced, facilitates the handling of the main thread. - Activity in
onCreate
andonResume
callback try to time-consuming operation.
10. What has led oom
The reason OOM generated : Out of memory,
Android system for each application are set a hard and fast condition:DalvikHeapSize
maximum threshold 64M/48M/24M
. If your application memory footprint close to this threshold, then try again if time memory allocation will cause OOM.
- Memory leaks more easily lead to OOM
- Processing large image. Compress image. Usually developers should pay attention to the frequent object creation and recovery.
- It may be an appropriate test:
ActivityManager.getMemoryClass()
can be used to query the current application of theHeapSize
threshold. By namingadb shellgetProp | grep dalvik.vm.heapxxxlimit
viewing.
How to avoid memory leaks:
1 to reduce the memory footprint the object):
- The use of more lightweight data structures :
consider alternatives where appropriate,HashMap
and other traditional data structures used specifically for the Android mobile phone data structures class research and developmentArrayMap/SparseArray。SparseLongMap/SparseIntMap/SparseBoolMap
more efficient.HashMap.put(string,Object);Object o = map.get(string);
It will lead to some unnecessary automatic boxing and unboxing.- Avoid the use of appropriate in the android
Enum
enumeration, instead of using an ordinary static constant . (General or Advocate multi-architecture design enumerate --- software; If you hit this enumeration requires extensive use of time should be more inclined to solve performance problems.). - Small memory footprint Bitmap object .
UseinSampleSize
: computing picture compression proportions picture compression, to avoid load causing big pictureOOM;
decodeformat
: Select a picture format decoding, andARGB_8888/RGB_565/ARGB_4444/ALPHA_8
can also be usedWebP
. - A smaller picture
resources pictures inside, whether there can continue to compress the space.
- Avoid the use of appropriate in the android
2) repeated use of memory objects:
object pooling technique,
two kinds:
Write your own;
use the existing system object pooling mechanism. For example,LRU(Last Recently Use)
algorithms.
- a.
ListView/GridView
Code reuse can see the situationConvertView
reuse.RecyclerView
InRecycler
the source code.- b.Bitmap multiplexing
Listview
, etc. To show a lot of pictures. Need to useLRU
caching mechanisms to reuse the picture.- c. Avoid
onDraw
creation method executed inside the object, to be multiplexed. Avoid memory jitter.- d common java-based issues ---
StringBuilder
such as
3) Avoid the object memory leaks
4) use of some memory optimization strategy : see the document
11.Android several ways of communication between Service with Activity
1) Binder
2) via the broadcast
The difference between the various versions of the API 12.Android
Several versions of the key features in mind: 3.0 / 4.0,4.4,5.0,6.0 / 7.0
13.Requestlayout, onlayout, onDraw, DrawChild differences and relations
RequestLayout()
Methods: will lead to calls Measure () method and layout (). Bit will need to determine whether the mark onDraw()
; onLayout()
: placed viewGroup
inside the child controls onDraw()
: Drawing view itself; ( ViewGroup
need to draw all the child controls inside) drawChild()
: re-draw the callback method each sub-view. child.draw (canvas, this, drawingTime) ;
14.invalidate () and postInvalidate () and use the difference between
invalidate()
: Refresh among the main thread; postInvalidate()
: refresh them in sub-thread; in fact, the final call is to invalidate, the principle of this mechanism is still sending a message to the main thread by thread work.
public void postInvalidate() {
postInvalidateDelayed(0);
}
public void postInvalidateDelayed(long delayMilliseconds) {
// We try only with the AttachInfo because there's no point in invalidating
// if we are not attached to our window
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
}
}
public void dispatchInvalidateDelayed(View view, long delayMilliseconds) {
Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view);
mHandler.sendMessageDelayed(msg, delayMilliseconds);
}
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_INVALIDATE:
((View) msg.obj).invalidate();
break;
15.Android animation framework implementation principle
Traditional animation framework: View.startAnimation();
the drawbacks: not click after the move. the reason? Implementation mechanism has a relationship with.
All of transparency, rotation, translation, scaling animation, are implemented in view of constantly refreshing the call to draw down.
Call canvas.translate (xxx), canvas.scaleX (xxx ) ... Xxx:. Matrix pixel matrix to control the data animation. I remember watching the source code, combined with more than just scaling the demo to see the source code.
16.Android each application allocated memory size?
See the specific mobile platforms, common are: 64M / 32M, etc.
17.LinearLayout 对比 RelativeLayout
Comparison Performance: LinearLayout
The performance than RelativeLayout
good.
Because the RelativeLayout
measurement twice. The (not set weight) by default LinearLayout
only measured once.
Why RelativeLayout
will measure twice? First, RelativeLayout
the sub-view arrangement is based on a relation interdependent, and this may be dependent on and independent of the order in view of the layout, is determined in each sub-view position, it needs about give each sub-row view sequence. And because RelativeLayout
allows horizontal and vertical interdependent, it is necessary to conduct a ranking measure horizontal and vertical, respectively.
18. optimized custom view
1) reduction in the onDraw
large number of computing and object creation inside and a lot of memory allocation.
2) should be used sparingly invalidate()
times.
. 3) View consuming operation inside layout. Decrease requestLayout()
avoid the UI system to re-traverse the entire tree. Mearsure
.
4) If you have a very complex layout, as this complex layouts directly using your own writing ViewGroup
to achieve. It reduces a tree hierarchy are all their own measurements and layout, to achieve the purpose of optimization. (Facebook often so dry)
19.ContentProvider
Tip: cross-process communication. Exchange data sharing between processes. ; Source code to a chop.
20.fragment life cycle
21. volley resolve
22. Android Glide source parsing
23. Android attribute animation features
24. How to ensure that a background service is not to be killed, what more energy efficient way?
25. touch event delivery process
26. Handler, Thread and HandlerThread difference
27. A description of a process network requests
See the full PDF version
(.... To be continued more complete project source code download graphic knowledge subsequent upload github)
can click on my contact me for a full PDF
( VX: mm14525201314 )