Android Interview Questions and answers (2), android Questions and answers
1. Activity-related. Launchmode, OnSaveInstnceState, and lifecycle.
Four default launchmodes and OnNewIntent callbacks.
OnNewIntent-> OnRestart-> OnStart-> onResume
OnActivity-> OnResume.
OnNewIntent, OnActivityResult?
OnNewIntent launchmode with singletask or singleInstance.
But if set these two mode. OnActivityResult will be called after startActivityforResult directly.
So normally, they can not called both.
OnSaveInstanceState:
There is a description of the Activity method: when the activity is about to be killed, the system will open this excuse for programmers to call it.
Then it passes the bundle information to OnCreate & Bundle.
This method will be called before OnStop, and the order of but and OnPause cannot be determined.
In some cases, the lifecycle does not go to OnDestroy, but some resources need to be released. At this time, it is best to be event-driven.
2. Fragment related technologies.
Fragment lifecycle: Activity & Fragement of four Android Components
Fragment and activity communication,
Fragmentmaneger. findFragmentById
Fragmentmaneger. findFragmentByTag,
Communication between fragment, setArgument.
GetActivity & addlistener.
Data storage and recovery. OnSaveInstanceState: the func of Fragment is synchronized with the Activity.
FragmentTransaction transaction = fm. benginTransatcion (); // start a transaction
Transaction. add ()
Add a Fragment to the Activity
Transaction. remove ()
Remove a Fragment from the Activity. If the removed Fragment is not added to the rollback stack (this will be detailed later), the Fragment instance will be destroyed.
Transaction. replace ()
Replacing the current one with another Fragment is actually a combination of remove () and add ~
Transaction. hide ()
Hiding the current Fragment is only invisible and will not be destroyed.
Transaction. show ()
Show Hidden Fragment
Detach ()
The view is removed from the UI. Unlike remove (), the fragment status is maintained by FragmentManager.
Attach ()
Re-create the view, attach it to the UI, and display it.
Transatcion. commit () // submit a transaction
Note: Fragment buddies often encounter errors such as inconsistent Activity states: State loss. The main reason is that the commit method must be called before Activity. onSaveInstance.
The above is basically all the methods used to operate Fragment. You can add, remove, or replace multiple operations when a transaction is started to commit.
It is worth noting that if you like to use Fragment, you must know which of these methods will destroy the view, which will destroy the instance, and which is only hidden to better use them.
Other problems: real full parsing of Android Fragment (below)
FragmentTransaction. addToBackStack (String): If it is a replace method, the current fragment will be removed. When all the back operations are performed, the fragment status will not be retained, but will only be retained.
Create. If it is the hide & add method, it will re-attch the previous fragment.
If the activity manages fragment, you can call all the public methods of fragment.
You can use findfragmentbyid & findfragmentbytag to locate the fragment.
Fragment can get the instance through getactivity.
When the screen is rotated, fragment will be repeatedly created. If the OnCreate bundle parameter is used, you can determine whether it is the first creation.
The default implementation bundle parameter of activity has content.
3. serialization technology, Parcable & Serializable.
Android inter-process communication data (I) ------ origin of parcel
Why serialization: for cross-process communication, inter-process communication should be in binary format, so serialization can restore data through deserialization.
Parcable is the serialization of memory machines, so the speed is fast.
4. fastJson & GSon uses package com. joyfulmath. publibrary. json; import com. alibaba. fastjson. JSON; import com. joyfulmath. publicutils. utils. traceLog;/*** @ author deman. lu * @ version on * use fastjson to resolve this issue */public class JsonUtils {public static <T> T parseObject (String jsonStr, Class <T> entityClass) {T ret = null; try {ret = JSON. parseObject (jsonStr, entityClass);} catch (Exception e) {TraceLog. e ("parseObject-something Exception with:" + e. toString ();} return ret;} public static String toJSONString (Object obj) {String ret = null; try {ret = JSON. toJSONString (obj);} catch (Exception e) {e. printStackTrace ();} return ret ;}}FastJson
5. multithreading, including handler, message logoff. ExecutorService.
Message Mechanism: android process/thread Management (1)-See this series for the message mechanism framework.
ExecutorService: thread pool, which can be used to close a thread and wait for it to close or directly close it.
6. ImageLoader principles, including Glide, picasso, and Fresco.
Picasso, an image loader produced by square, internally uses OKHttp to execute network requests.
Supports loading URLs, files, databases, and other paths. Images are not scaled,
Picasso & Glide
First, Glide is a secondary development based on Picasso.
With parameter: Glide can use Activity, fragment, and so on. Therefore, its loading can be bound to the lifecycle of actiivty.
Glide default image ARGB_565 piocasso: ARGB_8888
Glide loading Gif but Picasso cannot. but Glide will using much memory with gif.
Glide will cache with size of imageview, so each size of imageview will contains one copy.
Picasso will only has one cahce copy with fullsize. so glide is faster than picasso.
Glide helps reduce OOM.
/*** Created by deman on 2016/3/30. */public interface IImageLoader {void initLoader (Context context); void load (String path, ImageView view, int width, int height); void load (String path, ImageView view );}IImageLoader public class ImageLoadManger {private IImageLoader iImageLoader = null; private static ImageLoadManger sInstance = null; public static synchronized ImageLoadManger getsInstance () {if (sInstance = null) {sInstance = new ImageLoadManger ();} return sInstance;}/*** initManager * @ param context */public void initManager (Context context) {iImageLoader = new PicassoImageLoader (); iImageLoader. initLoader (context);}/*** load image with path * @ param imageView */public void load (String path, ImageView imageView) {if (null = iImageLoader) {throw new RuntimeException ("initManager has not been init");} iImageLoader. load (path, imageView );} /*** load image with path * @ param imageView * @ param width * @ param height */public void load (String path, ImageView imageView, int width, int height) {if (null = iImageLoader) {throw new RuntimeException ("initManager has not been init");} iImageLoader. load (path, imageView, width, height );}}ImageLoadMangerpublic class PicassoImageLoader implements IImageLoader {Picasso picasso; Context context; private void init () {picasso = new Picasso. builder (context ). build () ;}@ Override public void initLoader (Context context) {this. context = context; init () ;}@ Override public void load (String path, ImageView view, int width, int height) {if (null = path) {throw new RuntimeException ("uri is nul L! ");} If (width = 0 | height = 0) {throw new RuntimeException (" width & height is 0 ");} picasso. load (path ). resize (width, height ). into (view) ;}@ Override public void load (String path, ImageView view) {if (null = path) {throw new RuntimeException ("uri is null! ");} Picasso. load (path). into (view );}}PicassoImageLoader
Glide 500 K, Picasso 100 K
Fresco is an open-source image loading framework of facebook. It is based on the view level. SimpleDraweeView
Fresco, image pipline technology, three-level cache. Therefore, oom is not easy.
The first layer. Bitmap cache: On 5.0, java heap is used, and ashme memory is used for 5.0 to reduce the probability of GC.
The bitmap cache is cleared when the app arrives at the backend.
Layer 2: memory cache. Store the original compressed image.
Level 3: the disk cache will not be cleared.
Fresco has a great effect on memory saving, especially for low-end servers, which can reduce the chance of OOM.
The package is large and complex to use.
7. Combination of Adapter and ListView.
8. user Cookie design. The token process includes the login process.
Login design:
1) login jump
First, log on to the specified page, such as MainActivity,
In addition, after logging on, return to the previous page.
This 2 should be taken into account during login.
2) login password verification
The password is encrypted and transmitted in the form of parameters.
API uses https requests.
After successful login, you need to save userinfo locally so that you can log on automatically after exiting.
3) Automatic Login
Token mechanism. After each login is successful, a token is saved locally, and the token can save the expired information mechanism.
After the token expires, all the APIs that need to verify the token information will return the same code and then process it in a unified manner.
AlertDialog is displayed, allowing users to determine whether to log on.
9. encapsulation of network requests.
Volley
Volley + okhttp
Retrofit
Among them, Retrofit + okHttp + Picasso is uniformly produced by square.
The mainstream practice is to separate each framework to facilitate replacement.
Invalid fit + okHttp/Volley + Okhttp add fastjson, Glide/Fresco + buttnkinfe/dragger2/androidannotation + Rebotim.
The first day of learning the Android framework, okhttp & fit
10. Interaction between Android and H5.
H5 calls the andoriod code:
WebSettings. setJavaScriptEnabled (true );
MWebView. addJavascriptInterface (new DemoJavaScriptInterface (), "demo ");
Js callback, @ JavascriptInterface
Android calls JS
MWebView. loadUrl ("javascript: wave ()");
Redirect protocol:
When JS callback is performed, you can use shouldOverrideUrlLoading
Configure the URL as a protocol.
11. code obfuscation.
Enable obfuscation: androidstudio:
In gradle
buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } }
The key is minifyEnabled programming true. obfuscation compilation will open.
General need to configure proguard-rules.pro
Proguard4 big process:
Compression, bytecode optimization, confusion, pre-check.
Proguard can be configured with the following versions:
Proguard is in the sdk.
Proguard configuration process:
-Dontshrink does not compress input class files
-Dontoptimize: the input class file is not optimized.
-Dontobfuscate does not confuse input class files
12. android Packaging Machine
Including sdk commands.
How Android works: APk Generation Process
Packaging Process: aapt is used to generate the resource file R. java
Java compiler-> class file, and then dex compiled into the. dex file.
Resource placed by aapt
Package it into an apk file.
Other files will generate dex files. + The sign process is the APK, which may require compression and optimization.
13. Online Crash analysis and repair capabilities.
First, UnCaughtExceptionHandler is used to process and collect logs for crash that are not processed.
Step 3:
Collect logs and send them to the server
Prompt User to process
Save to SD
You need to save the proguardmapping file so that the online app can analyze the problem.
14. Memory leakage, including memory optimization, memory leakage, and use of the MAT tool.
See Android Advanced Interview Questions and answers
15. Monkey mechanism. How does Android develop a monkey test for an App.
Monkey is used to send random events on the screen. Generally, the frequency is more than. The main test result is a crash or ANR event.
The monkey object is apk.
Monkey event streams are random.
Monkey documentation: http://developer.android.com/guide/developing/tools/monkey.html
16. debugging tools, including the debugging functions of DDMS and android studio.
Androidstudio tools:
AndroidMonitor: StartMethodTracing test method execution time.
DDMS also has traceView, which has the same function.
Test View layout: hierachyviewer.
Debug: Advanced debugging functions:
Evaluate Expression: Under the run menu, this option is available, and its function is similar to watch, but it can test the execution statement.
Conditional breakpoint: in a loop, you are only interested in I = 9. What do you do? Right-click the breakpoint and select a condition.
Log breakpoint: it is also a very practical skill. When we need to print logs in some cases, but each compilation is very time-consuming, we can use Log breakpoint to print logs.
Do not modify source code. You can view the printed logs on the console in the Debug window.
Method breakpoint: The method breakpoint is the same as the function name. It is the breakpoint at the function entry and end.
Exception breakpoint: Run-> View blockpoint-> javaException.
Attribute breakpoint: When an attribute is modified or accessed, it is hard to find out in a complex multi-threaded environment. Run-> View blockpoint-> javaFieldWatchpoints.
DDMS: How to Use the DDMS tool in Android Studio?
17. unit testing, the use of Junit, including other testing frameworks.
public class ExampleTest extends InstrumentationTestCase { public void test() throws Exception { final int expected = 1; final int reality = 1; assertEquals(expected, reality); } public void test_2() throws Exception{ final int expected = 2; final int reality = 3; assertEquals(expected,reality); }}
It must be configured in configration.
18. advanced features of GIT: Stage, rebase, revert, stash, cherry pick & sub module
Stage is the index area, a concept that corresponds to the work area and history Area
Revert: cancels a Historical submission, but its submission record is retained, that is, it can be submitted to the remote database.
Reset: only the rollback history. The rollback content can be retained in the work area.
Cherry pick: A modification on branch2 that requires merge to branch3, but I just need this modification and use this command.
Sub module: it is not very useful.
19. Plug-in programming.
Opening an article
20. design patterns: familiar with common design patterns.
TBD.
21. hotfix technology.
TBD.
22. React + Native framework
TBD.
23. Message push principles
TBD.