preface

An awesome Android expert interview questions and answers (continuous updating…)

From dozens of top interview warehouse and more than 300 high-quality interviews summed up a comprehensive system of Android advanced interview questions.

Welcome to 2020 senior Android factory interview secrets, for you to escort jin SAN Silver four, direct Android factory foundation.

(⭐⭐⭐)


1. What is ANR and how to avoid it?

A: On Android, if your Application is not responsive for a period of time, the system will present the user with a dialog box called ANR (Application NotResponding) dialog box. Users can choose to keep the application running, but they don’t want to have to deal with this dialog every time they use your application. So, it’s important to design responsiveness in your program so that the system doesn’t show the ANR to the user.

The ANR takes five seconds for an Activity, 10 seconds for a BroadCastReceiver, and 20 seconds for a Service (both foreground).

If you have problems with your development machine, you can check /data/anr/ testamp.txt for the latest ANR information at the beginning.

  • The main thread is blocked by IO operations (network IO is not allowed in the main thread after 4.0).
  • There are time-consuming calculations in the main thread
  • Error operations in the main Thread, such as Thread.wait or thread. sleep, are monitored by the Android system. If either of the following conditions occurs, the ANR dialog box will be displayed
  • The application does not respond to user input events (such as keystrokes or touches) within 5 seconds
  • The BroadcastReceiver does not complete processing within 10 seconds
  • The Service could not process for 20 seconds at a certain time

Fixed:

1. Use AsyncTask to process time-consuming I/O operations.

2, use the Thread or HandlerThread, call Process. The setThreadPriority (Process. THREAD_PRIORITY_BACKGROUND) set priority, or still can reduce response Process, Because the default Thread has the same priority as the main Thread.

Instead of blocking the main Thread with thread.wait () or thread.sleep (), use a Handler to process worker Thread results.

4. Avoid time-consuming code in the Activity’s onCreate and onResume callbacks. IntentService is recommended for onReceive code in BroadcastReceiver to minimize time consumption.

Solution:

Put all time-consuming operations such as network access, Socket communication, querying large SQL statements, complex logic calculations, etc. into child threads, and then update the UI through handler.sendMessage, runonUIThread, AsyncTask, RxJava, etc. Make sure the user interface is smooth no matter what. If a time-consuming operation requires the user to wait, a degree bar can be displayed on the interface.

Further answer

2. What are the Activity and Fragment life cycles?

3. The Activity lifecycle when switching between vertical and horizontal screens

  • 1) Before Android 3.2 (API 13) :
    • When android:configChanges is not set for the Activity, the life cycle is called again for cutting the screen, once for cutting the landscape screen and twice for cutting the portrait screen.
    • When you set the Activity’s Android :configChanges=” Orientation “, the life cycle will be called again when the screen is cut, and the life cycle will be called once in both directions.
    • Set up the Activity of the android: configChanges = “orientation” | “keyboardHidden, cut screen not to call the Activity life cycle, But the onConfigurationChanges() method is called.
  • 2) Start with Android 3.2 (API 13)
    • Android :configChanges=” Orientation “when not setting the Activity android:configChanges=” Orientation”
    • Set up the Activity of the android: configChanges = “orientaion | keyboardHidden” landscape and vertical screen will switch to call a life cycle.
    • Set up the Activity of the android: configChanges = “orientation” | screenSize “when not to call the Activity of the life cycle, but will call onConfigurationChanges () method.

4. Defects and problems of AsyncTask, and explain its principle.

What is AsyncTask?

AsyncTask is a lightweight asynchronous task class that performs background tasks in a thread pool, then passes the progress and final results of the execution to the main thread and updates the UI in the main thread.

AsyncTask is an abstract generic class. It provides three generic parameters: Params, Progress, and Result. Params indicates the type of the parameter, Progress indicates the Progress and type of the background task, and Result indicates the type of the Result returned by the background task. If AsyncTask does not need to pass specific parameters, these three generic parameters can be replaced by Void.

About thread pools:

The AsyncTask thread pool, ThreadPoolExecutor, is shared within the process scope and is static, so AsyncTask controls all subclass instances within the process scope. Because of this limitation, when using the default thread pool, if the number of threads exceeds the maximum capacity of the thread pool, the thread pool will burst (after 3.0, the default is serial, no problem). In this case, you can try to customize the thread pool to work with Asynctask.

About the default thread pool:

In AsyncTask, the thread pool is a thread pool with CPU + 1 core thread, CPU * 2 + 1 maximum thread number, 128 work queue length, and 28 maximum wait queue number. However, you can customize the thread pool. Thread pools are handled by asyncTasks. Thread pools allow tasks to run in parallel. Note that data consistency is a problem in concurrent cases, where new data may be overwritten by old data. So if you want tasks to run serially, use SERIAL_EXECUTOR.

Differences between AsyncTask in different SDK versions:

The reason why the execute method of AsyncTask cannot execute the program immediately and the improvement scheme After checking the official documents, we found that when AsyncTask was first introduced, asynchronous tasks were executed sequentially in an independent thread, that is to say, only one task was executed at a time, not in parallel. Starting from 1.6, AsyncTask introduces a thread pool that allows up to five asynchronous tasks to be executed simultaneously. This means that only five threads are allowed to run, and the remaining threads must wait until one of the tasks is completed. In other words, if there are more than five AsyncTask instances in the process, the sixth one will have to wait if the first five are all running for a long time. This is a limitation of AsyncTask and is not fixed prior to 2.3. If your application requires a large number of background threads to perform tasks, you may have to abandon AsyncTask and create your own Thread pool to manage threads. It has to be said that while AsyncTask is easier to use than Thread, it can only run up to 5 threads at the same time, which greatly limits its use. You must carefully design your application to staggered AsyncTask time, try to do so in different times, or ensure that the number of AsyncTask time is not more than 5, otherwise you will encounter the problems mentioned above. Perhaps Google has realized the limitations of AsynTask and has made some changes to the AsyncTask API since Android 3.0: only one thread is started to perform one task at a time, and then the second task is executed, so that only one background thread is performing the submitted task.

Some questions:

1. Life cycle

Many developers assume that an AsyncTask created in an Activity will be destroyed when the Activity is destroyed. However, this is not the case. AsynTask is executed until the doInBackground() method completes, and then onCancelled(Result Result) method is executed if cancel(Boolean) is called; Otherwise, the onPostExecute(Result Result) method is executed. If we do not cancel AsyncTask before our Activity is destroyed, it may crash our application. Because the view it wants to process no longer exists. So, we have to make sure that the mission is canceled before the destruction activity. In short, we use AsyncTask to ensure that the AsyncTask is cancelled correctly.

2. Memory leaks

If AsyncTask is declared as a non-static inner class of the Activity, then AsyncTask retains a reference to the Activity. If the Activity has been destroyed and the background AsyncTask thread is still executing, it will continue to hold the reference in memory, causing the Activity to be unable to be reclaimed and causing a memory leak.

3. Results lost

A screen rotation or an Activity being killed by the system in the background will cause the Activity to be recreated. The previously running AsyncTask will hold a reference to the previous Activity that is invalid, and calling onPostExecute() to update the interface will no longer work.

4. Parallel or serial

Before Android1.6, AsyncTask is serial. After Android1.6, thread pool is used to process parallel tasks. However, starting from Android 3.0, in order to avoid concurrent errors caused by AsyncTask, one thread is used to execute tasks in serial. You can use the executeOnExecutor() method to execute tasks in parallel.

AsyncTask principle
  • AsyncTask has two thread pools (SerialExecutor and THREAD_POOL_EXECUTOR) and one Handler (InternalHandler). The thread pool SerialExecutor is used to queue tasks. The thread pool THREAD_POOL_EXECUTOR is used to actually execute the task, and InternalHandler is used to switch the execution environment from the thread pool to the main thread.
  • InternalHandler is a static Handler object. In order to be able to switch the execution environment to the main thread, this requires that the sHandler object be created on the main thread. Since static members are initialized when the class is loaded, the AsyncTask class must be loaded in the main thread, otherwise all asyncTasks in the same process will not work properly.

OnSaveInstanceState () and onRestoreIntanceState()

Activity onSaveInstanceState() and onRestoreInstanceState() are not lifecycle methods and, unlike lifecycle methods such as onCreate() and onPause(), they do not necessarily trigger. OnSaveInstanceState () is called when an Activity is destroyed by the system because the application encounters unexpected circumstances (e.g., running out of memory or the user pressing the Home button). But onSaveInstanceState() is not called when the user actively destroys an Activity, for example by pressing the return key in the application. In this case, the user’s behavior determines that the state of the Activity does not need to be saved. In general, onSaveInstanceState() is only good for temporary states, while onPause() is good for persistent data. Called before the activity is killed to save the state of each instance, ensuring that the state can be stored in onCreate(Bundle) or onRestoreInstanceState(Bundle). (The Bundle argument passed in is wrapped by onSaveInstanceState). This method is called before an activity is killed and restores its previous state when the activity returns at some point in the future. For example, if Activity B is started and is in front of Activity A, and at some point Activity A is going to be killed due to system recycling problems, A will have A chance to save its user interface state via onSaveInstanceState. The interface state can be restored by onCreate(Bundle) or onRestoreInstanceState(Bundle) when the user returns to Activity A in the future

Deep understanding of

6. What is the priority of processes in Android?

1. Foreground process:

The foreground process is the last to be killed if the system is running out of memory

2. Visible processes:

It can be an onPause Activity or a Service bound to it that is visible to the user but cannot interact with the user because it is out of focus

3. Service process:

The Service started by startService is not visible to the user, but it is concerned by the user. For example, the user is listening to the music in the non-music interface or downloading the file on the non-download page. The first two processes are terminated when the system needs space to run

4. Background processes

Which is running the onStop method and stop the program, but it is not the user’s current concern, such as QQ hanging in the background, then the process system once there is no memory will be killed first

5. Empty process:

A process that does not contain any application, such a process system is generally not allowed to exist

7. Why do Bunder pass objects need to be serialized? The difference between Serialzable and Parcelable?

Because the Bundle only supports basic data types when passing data, it needs to serialize to a stored or transportable intrinsic state (byte stream) when passing objects. Serialized objects can be transferred between the network, IPC (such as an Activity that starts another process, Service, and Reciver), or stored locally.

Serializable (Java built-in) :

Serializable stands for serialization, which means converting an object to a stored or transportable state. Serialized objects can be transferred over the network or stored locally.

Parcelable (Android only) :

In addition to Serializable, the same effect can be achieved with Parcelable. Instead of serializing an object, Parcelable splits the entire object into the data type supported by the Intent. This implements the function of passing objects.

The differences are summarized as follows:

8, animation,

  • Tween animation. By specifying the View at the beginning and end of the state and change mode, the content of the View to complete a series of graphic transformation to achieve animation effect. Alpha, Scale,Translate, Rotate.
  • Frame Frame animation. AnimationDrawable controls the animation-list.xml layout
  • Introduced in PropertyAnimation 3.0, the core idea of PropertyAnimation is the change of value.

Property Animation has two steps:

1. Calculate the attribute value

2. Set the property values for the properties of the target object, that is, apply and refresh the animation

The calculation of attributes is divided into three processes:

A process:

Calculate elapsed fraction. To perform an animation, you need to create a ValueAnimator and specify the start, end, and duration of the target object properties. During the entire animation process after the start call, ValueAnimator calculates a score between 0 and 1, representing the percentage of completed animations for the animation, based on the animation time that has been completed. 0 means 0% and 1 means 100%.

Process 2:

Interpolated fraction computing interpolation (animation change rate) interpolated fraction. After ValueAnimator has interpolated an animation score, it will invoke the current interpolator to interpolate a score. During interpolating, the percentage of the animation that has been interpolated will be added to the new interpolation calculation.

Third process:

Evaluating attribute Values When the interpolation score is calculated, ValueAnimator calls the appropriate TypeEvaluator based on the interpolation score to evaluate the attribute values in the motion. The above analysis introduces two concepts: Elapsed fraction and interpolated fraction.

Principle and characteristics:

1. Property animation:

Interpolator: The function is to calculate the percentage of the property change based on the percentage of time elapsed

Estimator: a class that calculates how many values a property has changed on the basis of one

In fact, it is the use of interpolators and estimators, to calculate the properties of the View at each moment, and then by changing the properties of the View to achieve the animation effect of the View.

2. View the animation:

It’s just that the image has changed, and the view’s actual location is still where it was.

3. Frame animation:

AnimatonDrawable is an animation that is played using an AnimatonDrawable after a series of images are defined in XML.

Their differences:

Property animation is the real implementation of view movement, tween animation to view movement is more like drawing a shadow in a different place, the actual object is still in the original place. When the repeatCount of the animation is set to infinite, if the animation is not stopped when the Activity exits, the property animation will cause the Activity to be unable to be released, resulting in a memory leak, whereas the tween animation is fine. XML file tween animation, reuse rate is very high. In the Activity switch, window popup and other scenarios have a good effect. When using frame animation, be careful not to run out of memory by using too many extremely large images.

Why is property animation still clickable after moving?

When we play the tween animation, the changes we see are only temporary. Property animation, on the other hand, what it changes is updated to the matrix corresponding to the View, so when the ViewGroup dispatches the event, it correctly converts the current touch coordinates to the matrix changed coordinates, which is why playing the tween animation doesn’t change the touch area.

9. Context related

  • The Context of an Activity is different from that of a Service or Application. The Activity inherits the ContextThemeWraper. The others are inherited from ContextWrapper.

  • 2. Each Activity and Service and Application Context is a new ContextImpl object.

  • GetApplication () is used to get an Application instance, but this method can only be called in activities and services. That’s probably true for most applications in an Activity or a Servic, but if you want to get an instance of an Application in a different context, like a BroadcastReceiver, You can use the getApplicationContext() method, which has a wider scope than getApplication(). Any instance of a Context, We can get our Application object by calling the getApplicationContext() method.

  • 4, When creating a dialog, you cannot use the Application context, only the Activity context.

  • The number of contexts is equal to the number of activities + the number of Services +1, which is Application.

10. New features of Android versions

Android5.0 new features
  • MaterialDesign design style
  • Support for 64-bit ART virtual machines (ART virtual machines in 5.0, Dalvik before 5.0). The difference is:

Dalvik, bytecode needs to be converted to machine code (JIT) by the just-in-time compiler each time it is run. ART, bytecode is precompiled into machine code (AOT) when the application is first installed.

  • Notification details can be designed by users themselves
Android6.0 new features
  • Dynamic Rights Management

  • Support quick charging switch

  • Support folder drag and drop applications

  • Added professional mode to camera

Android7.0 new features
  • Multi-window support

  • V2 signature

  • Enhanced Java8 language patterns

  • Night mode

New features for Android8.0 (O)
  • Optimize the notification

    Notification Channel Notification flag Sleep Notification Timeout Notification Set Notification clear

  • Picture in picture mode: list the Activity set android: supportsPictureInPicture

  • Background restrictions

  • Self-filling frame

  • System optimization

  • And so on and so forth

New features for Android9.0 (P)
  • Indoor WIFI positioning

  • “Bangs” screen support

  • Security enhancements

  • And so on and so forth

Android10.0 (Q) is currently exposing new features
  • Night mode: Dark mode can be set for all apps, including those on your phone.
  • Desktop mode: Provides a PC-like experience, but is no substitute for the PC.
  • Screen recording: Enable by long pressing “Screen snapshot” in the “Power” menu.

11, Json

JSON is a syntax for storing and exchanging text information. Similar to XML, but smaller, faster, and easier to parse than XML. JSON is a lightweight text data interchange format that is language independent. Being descriptive and easier to understand, objects can contain multiple name/value pairs, such as:

{"name":"zhangsan" , "age":25}
Copy the code

Use Google’s GSON package for parsing to introduce dependencies in Android Studio:

The compile 'com. Google. Code. Gson: gson: 2.7'Copy the code

Note that the variable name in the entity class must be the same as the value name in the JSON.

Example:

1. Parse into entity classes:

Gson gson = new Gson();
Student student = gson.fromJson(json1, Student.class);
Copy the code

Int array ();

Gson gson = new Gson();
int[] ages = gson.fromJson(json2, int[].class);

    
Copy the code

3, parse directly into List.

Gson gson = new Gson();
List<Integer> ages = gson.fromJson(json2,  newTypeToken<List<Integer>>(){}.getType);

Gson gson = new Gson();
List<Student> students = gson.fromJson(json3, newTypeToke<List<Student>>(){}.getType);
Copy the code
Advantages:
  • Lightweight data interchange format
  • Easier to read and write
  • Easy machine parsing and generation
Disadvantages:
  • Less semantic and less intuitive than XML

12, What kinds of XML parsing classes are available in Android? Which ones are officially recommended? How do they work and how do they differ?

The DOM parsing

Advantages:

1. The XML tree is completely stored in memory, so its data structure can be modified directly.

2. You can access any node in the XML tree at any time through this parser.

3. The DOM parser API is also relatively simple to use.

Disadvantages:

If the XML document is large, reading the document into memory is non-resource consuming.

Usage Scenarios:

  • DOM is the official W3C standard for representing XML documents in a platform – and language-independent manner.
  • The DOM is a collection of nodes organized in a hierarchy. This hierarchy allows openers to look for specific information in the tree. Analyzing the structure usually requires loading the entire document and constructing a hierarchy before any work can be done.
  • DOM is based on an object hierarchy.
SAX parsing

Advantages:

SAX is less memory intensive because it lets the developer decide which tags to process. SAX’s extensibility is especially good when the developer only needs to work with part of the data contained in the document.

Disadvantages:

XML parsing in SAX requires sequential execution, making it difficult to access different data in the same document. In addition, the analytic coding program based on this method is also relatively complex.

Usage Scenarios:

This method is useful when there is a large amount of data in the document without traversing or analyzing all of the data. This method does not read the entire document into memory, but only to the document marker required by the program.

Xmlpull parsing

The Android SDK provides an XMLpullAPI. Xmlpull is similar to SAX in that it operates on a stream file, which calls back handlers written by the developer based on node events. Because of stream-based processing, BOTH XMLPull and SAX are less memory intensive and do not present all nodes in memory as a tree of objects as DOM does; xMPull is more concise than SAX and does not require scanning the entire stream.

13. The difference between Jar and Aar

The Jar contains only code, and the AAR contains not only code but also resource files, such as drawable files and XML resource files. For Android libraries that don’t change very often, we can refer directly to an AAR to speed up compilation.

14. How much memory does Android allocate for each application

Android applications are typically limited to 16 megabytes of memory, but some have 24 megabytes. In recent years mobile phone development is rapid, can allocate 200 MB or so commonly, and specific model is concerned.

15. Update the UI

  • Activity.runOnUiThread(Runnable)
  • View.post(Runnable), view. postDelay(Runnable, long)
  • Handler
  • AsyncTask
  • Rxjava
  • LiveData

16. Use method of ContentProvider.

Cross-process communication to realize data interaction and sharing between processes. Context getContentResolver() to get the instance, using Uri matching to add, delete, change, and query data. ContentProvider uses tables to organize data, and ConentProvider considers the data to be a table, regardless of the source, and organizes the data into tables.

17. Usage scenarios and features of Thread, AsyncTask and IntentService.

  1. A Thread that runs independently of an Activity. If the Activity does not stop after finish, the Thread or run method will continue to execute.

  2. AsyncTask encapsulates two thread pools and a Handler (SerialExecutor for queuing, THREAD_POOL_EXECUTOR for the actual executing task, and Handler to switch the worker thread to the main thread) that must be created in the UI thread, The execute method must be executed in the UI thread. A task instance can only be executed once, and multiple exceptions are thrown for network requests or simple data processing.

  3. IntentService: Handles asynchronous requests, implements multi-threading, and handles time-consuming operations in onHandleIntent. Multiple time-consuming tasks are executed one by one and end automatically.

Merge. ViewStub.

Merge: Reduces view levels. You can delete unnecessary levels.

ViewStub: loads on demand, reduces memory usage, speeds up rendering, and does not support merge tags.

Is the startActivity of an activity different from the startActivity of a context?

(1) Start a new Activity with McOntext. startActivity(intent)

(2) If you start an Activity from another Context, you must set the intent Flag:

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ; 
mContext.startActivity(intent);
Copy the code
20, How to create Dialog box in Service?

1. After we get the Dialog object, we need to set its type:

dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)
Copy the code

2. Add permissions to Manifest:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINOW" />
Copy the code

21. What is the difference between Asset directory and RES directory?

Assets: the corresponding tags are not generated in the R file. The assets stored here will be packaged into the program installation package. (Access these files through the AssetManager class)

Res: Id tags are generated in the R file. If resources are used during packaging, they are packaged in the installation package. If resources are not used, they are not added to the installation package.

Res /anim: Stores animation resources.

Res/RAW: Just like the files under Asset, the package is directly exported to the program installation package (which is mapped to the R file).

22. How does Android speed up an Activity?

  • No time-consuming operations are performed in onCreate()

Break down the View of the page and place it in AsyncTask step by step, preferably with a Handler. So the user see is a hierarchical step by step View display, is not to see a black screen, and then show all the View. It is better to make animation, the effect is more natural.

  • The goal with multithreading is to minimize onCreate() and onReume() time so that the user can see and manipulate the page as quickly as possible.

  • Reduce main thread blocking time.

  • Improve the efficiency of Adapter and AdapterView.

  • Optimize the layout file.

23. Handler mechanism

The flow chart of the Android message loop is as follows:

The roles involved are as follows:

  • “Message” : message.
  • MessageQueue: Message queue that stores and manages messages and messages sent by the Handler. Read will automatically delete messages, single linked list maintenance, insert and delete advantages. In its next() method, it loops indefinitely, constantly determining if there is a message, returning it and removing it.
  • Looper: Message Looper, which is responsible for thread association and Message distribution. The thread gets the Message from MessageQueue and distributes it to the Handler. Looper is created when it is created

MessageQueue, the message loop starts when the loop() method is called, in which the next() method of MessageQueue is repeatedly called. When there is a message, it will be processed, otherwise it will be blocked in the next() method of MessageQueue. MessageQueue’s quit() is called when Looper’s quit() is called, next() returns null, and the loop() method exits.

  • Handler: Message Handler, responsible for sending and processing messages, facing developers, providing apis, and hiding the implementation details behind them.

The whole message cycle process is relatively clear, to be specific:

  • 1. The Handler sends a Message to MessageQueue via sendMessage().
  • 2. Looper retrieves the Message of the trigger condition through loop() and passes the Message to the corresponding Target handler.
  • The target handler calls its own handleMessage() method to handle messages.

In fact, the Java layer is not the only one involved in the flow of the message loop; much of the important work is done in the C++ layer. Let’s look at the calling relationships of these classes.

Note: Dashed lines represent association relationships, solid lines represent invocation relationships.

Among these classes, MessageQueue is the bridge between Java layer and C++ layer, and functions related to MessageQueue and Looper are completed by MessageQueue Native method, while other classes connected by dotted lines only have association relationship, without direct call relationship. The bridge through which they are related is MessageQueue.

conclusion
  • Messages sent by the Handler are stored and managed by MessageQueue, and Looper is responsible for calling back messages to handleMessage().
  • Thread conversion is done by Looper, and the thread of handleMessage() is determined by the thread of the looper.loop () caller.
Causes of memory leaks caused by handlers and the optimal solution

Handler allows us to send delayed messages that will leak if the user closes the Activity during the delay. This leak happens because Message holds Handler, and because of Java’s nature, inner classes hold external classes, so the Activity is held by Handler, which eventually leads to Activity leaks.

Solution: defines Handler into a static inner class, internally holds the Activity of weak references, and during the Acitivity onDestroy () call Handler. RemoveCallbacksAndMessages (null) remove all messages in a timely manner.

Why can we use Handler directly on the main thread without creating Looper?

Usually we think of an ActivityThread as the main thread. It is not actually a thread, but a manager of the main thread operations. The Looper.PrepareMainLooper () method is called in activityThread.main () to create the Looper for the main thread, and the loop() method is called, so we can use the Handler directly.

So we can use the interception mechanism Callback to intercept Handler messages. For example, Hook ActivityThread.mh is handled in most plug-in frameworks.

Looper of the main thread is not allowed to exit

The main thread is not allowed to exit, which means the APP will hang.

What can a Callback do hidden in a Handler?

Handler.Callback has priority in handling messages. When a message is processed and intercepted (returns true), Handler’s handleMessage(MSG) method is not called. If a Callback processes a message but does not intercept it, it means that a message can be processed by both Callback and Handler.

The best way to create a Message instance

In order to save overhead, Android has designed a recycling mechanism for Message, so we try to reuse Message when using to reduce memory consumption:

  • Message.obtain() via the static method of Message;
  • Through Handler’s public method handler.obtainMessage().
The correct position to bounce Toast in child thread

In essence, the Toast implementation relies on the Handler and can be modified as required by the child thread using the Handler, as well as the Dialog.

Great Looper mechanism
  • Post Runnable to the main thread for execution;
  • Use Looper to determine if the current thread is the main thread.
Is the main thread running in an endless loop particularly CPU intensive?

If the main thread MessageQueue has no message, it blocks in the nativePollOnce() method of the loop queue.next(), and then the main thread releases CPU resources and goes to sleep. Wake up the main thread by writing data to the pipe end until the next message arrives or a transaction occurs. The epoll mechanism adopted here is an IO multiplexing mechanism, which can monitor multiple descriptors at the same time. When a descriptor is ready (read or write ready), it immediately notifies the corresponding program to carry out read or write operations. In essence, it is synchronous I/O, that is, read and write is blocked. Therefore, the main thread is dormant most of the time and does not consume a lot of CPU resources.

Handler postDelay How is this delay implemented?

Handler. postDelay is not put into MessageQueue after waiting for a certain time, but directly enter MessageQueue, which is realized by combining MessageQueue time sequence and wake up.

How to guarantee message order in msG. postDelay case?

Handler doesn’t understand why he should jump ship.

24. Can program A receive program B’s broadcast?

Yes, use the global BroadCastRecevier to communicate across processes, but note that it can only passively receive broadcasts. In addition, LocalBroadCastRecevier is limited to interbroadcast communication for this process.

25. Data loading involves more pagination, how do you implement it?

Pagination loading is to load data page by page, when sliding to the bottom, no more data to load, we can manually call the interface, refresh RecyclerView.

26. What are the rules for defining Javabeans when parsing JSON through Gson provided by Google?

1). Implement Serializable

2). Privatize attributes and provide get and set methods

3). Provide a no-parameter construct

4). The property name must be the same as the property name in the JSON string (because Gson uses Java reflection to parse the json string)

27. What are the differences between json parsing methods?

1. SDK provides JSONArray, JSONObject

2. Gson, provided by Google, implements object deserialization (converting json string to object type) through fromJson() and implements object serialization (converting object type toJson string) through toJson().

28. Knowledge of thread pools.

Thread pools in Android are thread pools that implement different features, either directly or indirectly, by configuring ThreadPoolExecutor. The most common Android classes with different thread pools are FixThreadPool, CachedhreadPool, SingleThreadPool, and ScheduleThreadExecutr.

1).FixThreadPool

Only core threads, and a fixed number of threads, will not be reclaimed. When all threads are active, because the queue size is not limited, new tasks will wait to execute.

Advantages: Faster response to external requests.

2).SingleThreadPool

There is only one core thread, ensuring that all tasks are completed in sequence in the same thread. So you don’t have to deal with thread synchronization.

3).CachedThreadPool

Only non-core threads, the maximum number of threads is very large. When all threads are active, new threads are created for new tasks. Otherwise, idle threads are used (60 seconds, which will be reclaimed, so there is a possibility of 0 threads in the thread pool) to process tasks.

Advantages: Any task is executed immediately (the SynchronousQuue of a task queue is equivalent to an empty collection); It is better for performing a large number of small tasks.

4).ScheduledThreadPool

The number of core threads is fixed, and there is no limit to the number of non-core threads that are not working.

Advantages: Perform scheduled tasks and repetitive tasks with a fixed period

Memory leak, how to find, how to produce memory leak?

1. Memory leak caused by resource object not closed

Description: Resource objects, such as Cursor, File, etc., use some buffer, we should close them when not in use, so that their buffer can reclaim memory in time. Their buffering exists both inside and outside the Java Virtual machine. If we simply set its references to NULL without closing them, we tend to cause a memory leak. Because some resource objects, such as SQLiteCursor(finalize(), will call close() to close if we don’t close it), if we don’t close it, the system will close it when we reclaim it, but this is too inefficient. Therefore, when a resource object is not in use, call its close() function to close it, and then set it to NULL. Make sure our resource object is closed before our program exits.

The program often carries on the query database operation, but often does not close the situation after using Cursor. If our query result set is relatively small, the memory consumption is not easy to be found, and the memory problem will occur only in the case of a large number of operations at a constant time, which will bring difficulties and risks to future testing and troubleshooting.

2. No cached convertView is used when the Adapter is constructed

Take the BaseAdapter that constructs the ListView as an example, in which methods are provided: Public View getView(int Position, ViewconvertView, ViewGroup parent) provides the View object required by each item to the ListView. The ListView initially instantiates a number of View objects from the BaseAdapter based on the current screen layout, and the ListView caches these view objects. When you scroll up the ListView, the view object of the original top List item is reclaimed and used to construct the new bottom list item. This construction is done by the getView() method, and the second argument to getView(), View convertView, is the cached View of the List item (convertView is null if there is no View object in the cache at initialization). As you can see, if we don’t use convertView and instead re-instantiate a View object in getView() each time, we will waste resources, time, and memory. ListView to recycle the list of item view objects can view: the process of the android. The widget. AbsListView. Java — > voidaddScrapView (view scrap) method. Sample code:

public View getView(int position, ViewconvertView, ViewGroup parent) { View view = new Xxx(...) ; . . return view; }Copy the code

Fixed example code:

public View getView(int position, ViewconvertView, ViewGroup parent) { View view = null; if (convertView ! = null) { view = convertView; populate(view, getItem(position)); . } else { view = new Xxx(...) ; . } return view; }Copy the code

3. Call recycle() to release memory when the Bitmap object is not in use

If a Bitmap is not in use, the bitmap.recycle () method can be used to recycle the pixels of the Bitmap, but this is not necessary, depending on the situation. Take a look at the comments in the code:

/* •Free up the memory associated with thisbitmap’s pixels, and mark the •bitmap as “dead”, Throw an exception if getPixels() or •setPixels() is called, And will drawnothing. This operation cannot be •reversed, So it should only be called ifyou are sure there are no •further uses for the bitmap. This is anadvanced call, And normally need •not be called, Since the normal GCprocess will free up this memory when • There are no more references to thisbitmap. /

4. Try to use the application context instead of the activity-related context

This is a very insidious memory leak situation. There is a simple way to avoid context-related memory leaks. The most obvious one is to keep the context out of its own scope. Use the Application Context. The lifetime of the context is the same as the lifetime of your application, not dependent on the lifetime of the activity. If you want to keep a long-running object that needs a context, remember to use the Application object. You can call the Context. GetApplicationContext () or Activity. GetApplication (). See this article for more on how to avoid Android Memory Leaks.

5. Memory leakage caused by uncanceled registration

Some Android programs may reference objects (such as registration mechanisms) from our Android program. Even if our Android program has ended, other referencing programs still have references to an object in our Android program, and the leaked memory cannot be garbage collected. UnregisterReceiver is not called after registerReceiver is called. For example, if we want to listen on the phone service in the system to get some information (such as signal strength) in the LockScreen, we can define a PhoneStateListener object in the LockScreen. Register it with the TelephonyManager service as well. For the LockScreen object, a LockScreen object is created when the LockScreen is displayed, and released when the LockScreen disappears. However, if we forget to cancel our previously registered PhoneStateListener object when releasing the LockScreen object, the LockScreen will not be garbage collected. If the LockScreen is continuously displayed and disappeared, the system_process will eventually hang due to OutOfMemory due to a large number of LockScreen objects that cannot be retrieved. Although some systems seem to automatically cancel registrations (not in time, of course), we should explicitly cancel registrations in our programs and cancel all registrations at the end of the program.

6. Memory leaks caused by objects in the collection not being cleaned

We often add references to objects to the collection, but when we don’t need the object, we don’t clear it out of the collection, so the collection gets bigger and bigger. The situation is even worse if the collection is static.

Memory leaks can be found using the AndroidProfiler tool or MAT that comes with Android Studio, or using LeakCanary from Square products.

AndroidProfiler’s MEMORY tool

Run the program to check the memory analysis of each page. First, open and close the page repeatedly 5 times and then receive GC (click on the trash can icon in the upper left corner of Profile MEMORY). If total MEMORY has not been restored to its previous value by this time, a MEMORY leak may have occurred. Click the Heap Dump button next to the trash can icon in the upper left corner of Profile MEMORY to view the current MEMORY stack. Select Search by package name to find the Activity being tested. If multiple instances are referenced, a MEMORY leak has occurred.

2. Use MAT:

1. Run the program, run all functions once, make sure there is no problem, exit the program completely, and trigger GC manually. Then run adb shell dumpsys meminfo packagename -d to check whether the number of Views and Activities in the Objects group is 0. If not, run the Leakcanary command to check for possible memory leaks. Finally, through MAT analysis, and so on, the improvement is satisfactory.

1, Before using MAT, use the Memory in the Profile of AS to obtain the heap Memory snapshot file to be analyzed. Hprof, and then dump the current snapshot file. Hprof, finally, compare the two, if the memory division is obvious, memory leakage may occur. (Note :MAT needs the standard. Hprof file, so the memory snapshot file is dumped after GC in the Profiler of AS. Hprof must be manually converted by the Hprof-conv program under the Android SDK platform-tools to be opened by MAT.)

2. Then, use MAT to open the two previously saved. Hprof files and open the Overview interface, where there are four actions, including Histogram and Dominator Tree.

Dominator Tree: A Dominator Tree that lists objects and their referenced objects in descending order of size, focusing on reference relationship analysis. Select Group by Package, find the current class you want to detect (or use the Regex at the top), see if it has the right number of objects, and if it has too many, determine that a memory leak has occurred. Then, right-click the class and select the Exclude All Phantom /weak/soft etc. References option in Merge Shortest Paths to GC Root to see the GC strong references chain for the class. Finally, the object that finally strongly references the class can be seen through the reference chain.

Histogram focuses on quantitative analysis. The usage is similar to Dominator Tree.

3. Memory leaks in complex cases were detected by comparing hprof files:

General contrast method: Select the Dominator_tree /histogram you want to Compare under Navigation History, right-click and select Add to Compare Basket. Then click the red exclamation mark to Compare the Results in the Compare Basket column to generate the Compared Tables. At the top Regex type the classes you want to test and look at the reference relationships or the number of objects to analyze.

A quick comparison method for Historam: Directly select the Compare to another Heap Dump above Histogram and select the Historam of the hprof file to be compared.

What is the order in which classes are initialized?

(Static variables, static code blocks) > (variables, code blocks) > constructor

The structure of JSON?

Json is a lightweight data exchange format. Json is simply an object and an array, so these two structures are objects and arrays, which can represent various complex structures

1, object: object is represented as “{}” expanded content, the data structure is {key: value,key: value,… } in object-oriented language, key is an attribute of an object, value is the corresponding attribute value, so it is easy to understand the value method of object.

2, array: array in JSON is the contents of the expanded parentheses “[] “, the data structure is [” Java “,”javascript”,” VB “,… As in all languages, the value is obtained by index. The field value can be a number, a string, an array, or an object. After object, array two kinds of structure can be combined into complex data structure.

How to set ViewPager to initialize only the current Fragment each time and leave the rest uninitialized?

Define a LazyLoadFragment base class. Use setUserVisibleHint and lifecycle method to load data by judging the Fragment state, and open the interface for data loading for use by subclasses. Then implement the requestData method in a subclass Fragment. An isDataLoaded variable is added to avoid reloading data. Considering that data sometimes needs to be refreshed, a parameter judgment is provided to force the refresh.

public abstract class LazyLoadFragment extends BaseFragment {
    protected boolean isViewInitiated;
    protected boolean isDataLoaded;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewInitiated = true;
        prepareRequestData();
    }
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        prepareRequestData();
    }
    public abstract void requestData();
    public boolean prepareRequestData() {
        return prepareRequestData(false);
    }
    public boolean prepareRequestData(boolean forceUpdate) {
        if (getUserVisibleHint() && isViewInitiated && (!isDataLoaded || forceUpdate)) {
            requestData();
            isDataLoaded = true;
            return true;
        }
        return false;
    }
}
Copy the code

Why did Android introduce Parcelable?

To be sure, both support serialization and deserialization operations.

The biggest difference between them lies in the different storage media. Serializable uses I/O read and write to store on hard disks, while Parcelable uses I/O read and write to store directly in memory. Obviously, memory reads and writes are usually faster than IO reads and writes, so Parcelable is preferred when passing data in Android.

Serializable will use reflection, serialization and deserialization process requires a lot of I/O operations, Parcelable own implementation of marshalling and unmarshalling (reflection) operation, data is also stored in Native memory, It’s much faster.

Have you tried to simplify the use of Parcelable?

The Parcelable plug-in (Android Parcelable Code Generator) is used to serialize the entity class.

37. What should I pay attention to when using Bitmap?

1, to select the appropriate image size (bitmap type) :

ARGB_4444 Each pixel occupies 2 bytes of memory ARGB_8888 each pixel occupies 4 bytes of memory (default) RGB_565 Each pixel occupies 2 bytes of memoryCopy the code

2. Reduce the sampling rate. InSampleSize BitmapFactory. The Options parameter, the use of the Options. The first inJustDecodeBounds is set to true, only to read the size of the images, After getting the size of the image and comparing it with the size to display, calculate the inSampleSize value through calculateInSampleSize() function, and get the value. Read image resource options. InJustDecodeBounds set to false.

3. Memory overuse. That is, through soft reference (the memory will be reclaimed when it is insufficient), the memory block is reused and the bitmap does not need to apply for a new piece of memory, thus avoiding the one-time memory allocation and reclamation, thus improving the operating efficiency.

4. Recycle memory in time using the recycle() method.

5. Compress the image.

38, Oom can try catch?

There is only one situation in which this is possible:

If a large object is declared in the try statement, resulting in OOM, and we can confirm that OOM is caused by the object declaration in the try statement, then in the catch statement, we can release these objects, solve OOM’s problem, and continue to execute the rest of the statement.

But this is usually not the right thing to do.

There are more effective ways to manage memory in Java besides explicitly catching OOM: SoftReference, WeakReference, hard disk cache, etc. Multiple GCS are triggered before the JVM runs out of memory, and these GCS reduce the efficiency of the program. If the OOM is not caused by an object in the try statement (such as a memory leak), then the OOM will continue to be thrown in the catch statement.

Have you met multi-process scenario?

1. In the new process, start the foreground Service and play music. 2, a mature application must be more modular. First of all, multi-process development can solve OOM problem for application, because Android’s memory limit is for process, so when we need to load large image and other operations, we can perform in a new process, avoid OOM main process. And if the image viewer process opens a large image and the Java Heap fails to allocate memory, the process crash does not affect the use of my main process.

40, when to call canvas.save () and canvas.restore ()

Save: Saves the Canvas state. After save, operations such as translation, scaling, rotation, miscutting and clipping of Canvas can be called.

Restore: Restores the previously saved state of the Canvas. Prevent operations performed on Canvas after save from affecting subsequent drawing.

Save and restore are used in pairs (restore can be less than save, but not more), and if restore is called more times than save, an Error is raised. The timing of the save and restore operations can result in different graphs being drawn.

Adding and deleting tables does not involve data migration in database upgrade, but modifying tables involves migrating the original data. The upgrade method is as follows:

Name existing tables as temporary tables. Create a new table. Import data from a temporary table into a new table. Delete temporary tables.

There are two ways to upgrade a cross-version database, as follows:

Step by step, determine the differences between the adjacent version and the current version, V1 to V2,V2 to V3, and so on. Upgrade across levels, determine the differences between each version and the current database, and write special upgrade large code for each case.

public class DBservice extends SQLiteOpenHelper{
    private String CREATE_BOOK = "create table book(bookId integer primarykey,bookName text);";
    private String CREATE_TEMP_BOOK = "alter table book rename to _temp_book";
    private String INSERT_DATA = "insert into book select *,'' from _temp_book";
    private String DROP_BOOK = "drop table _temp_book";
    public DBservice(Context context, String name, CursorFactory factory,int version) {
    super(context, name, factory, version);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_BOOK);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    switch (newVersion) {
        case 2:
            db.beginTransaction();

            db.execSQL(CREATE_TEMP_BOOK);
            db.execSQL(CREATE_BOOK);
            db.execSQL(INSERT_DATA);
            db.execSQL(DROP_BOOK);

            db.setTransactionSuccessful();
            db.endTransaction();

            break;
    }
}
Copy the code

Compile-time annotations and runtime annotations

RunTime annotations (RunTime) using reflection to obtain information is relatively wasteful, corresponding to @Retention (retentionPolicy.runtime).

Compile time annotations, and the tools APT and Javapoet for handling Compile time annotations, correspond to @Retention(retentionPolicy.class). Apt +javaPoet is also widely used in some large open source libraries, such as EventBus3.0+, page routing ARout, Dagger, Retrofit, etc. Annotations are not only used by reflection, but also can be processed by apt during compilation

43. Bitmap Recycler is relevant

In Android, Bitmap storage is divided into two parts, one is Bitmap data, the other is Bitmap reference. In the era of Android2.3, Bitmap references are placed in the heap, while Bitmap data is placed in the stack, requiring users to call the recycle method to manually reclaim memory. After Android2.3, the whole Bitmap, including data and references, is placed in the heap. The entire Bitmap collection is left to the GC, and the recycle method is no longer needed.

Problems caused by Bitmap Recycler: Images cannot be displayed even if they are rotated by less than the Angle between two pixels, so the system can consider images unchanged. In this case, the system directly references the same object to avoid memory waste.

44, Strong reference set to NULL, will be reclaimed?

Memory occupied by objects is not immediately freed. If a reference to an object is set to null, it simply disconnects the reference to the object in the current thread stack frame. The garbage collector is a thread running in the background and scans the object reference only when the user thread reaches a safe point or safe zone. If the object is not referenced, it marks the object. There is still no immediate release of the object memory, because some objects are recoverable (references are recovered in the Finalize method). Object memory is cleared only if it is determined that the object cannot recover a reference.

45. Why does the Bundle transfer data need serialization?

Serialization: to convert an object into a state that can be stored or transferred. There are three basic reasons for serialization:

1. Permanently save the object and its byte sequence to a local file.

2. Objects are transferred on the network.

3. Objects are passed between IPC.

Is there a limit to the transmission of broadcast data, how much, why to limit?

In an Intent, the size of the data to be transmitted is limited to 1MB. In an Intent, the size of the data to be transmitted is limited to 1MB. In an Intent, the size of the data to be transmitted is limited to 1MB. If more data is passed at one time than the limit, an exception occurs.

Different vendors behave differently. It may be that the vendor has changed the size of the limit, or the same object may have different sizes on different machines.

Delivering big data should not be intEnts; Consider using contentProviders or simply anonymous shared memory. In simple cases segmented transmission can be considered.

47. Do you know hardware acceleration?

Hardware acceleration is to use the excellent computing ability of GPU to accelerate the rendering speed, while the usual software-based rendering mode is to completely use CPU to complete the rendering.

1. Hardware acceleration was introduced from API 11 and enabled by default only after API 14. Standard drawing operations and controls are supported, but for custom views or special drawing functions, hardware acceleration needs to be turned off.

2. We face does not support hardware acceleration, it is necessary to restrict hardware acceleration, the compatibility problem because hardware acceleration is the View of the mapping function into use OpenGL function into do the actual drawing, then will inevitably exist in the OpenGL doesn’t support the original receipt function, for these drawing function, will fail.

3. Hardware acceleration consumption problem, because it is using OpenGL, need to load the system OpenGL into memory, OpenGL API call will take up 8MB, but in fact will take up more memory, and the use of hardware will increase power consumption.

4. Another advantage of hardware acceleration is the design of Display List, with which we don’t need to perform a lot of code every time we redraw. Software-based draw mode redraws all the controls in the dirty area, whereas display just updates the list and draws the controls in the list.

  1. Cpus are better at complex logic control, while Gpus are better at math thanks to a lot of ALU and parallel architecture.

ContentProvider permission management (read/write separation, permission control – down to table level, URL control).

For the data exposed by ContentProvider, it should be stored in its own application memory. For some data stored in external memory, there is no limit to access, so using ContentProvider makes no sense. For ContentProvider, there are many permissions. You can configure node attributes in the Androidmanifest.xml file, using the following attributes:

  • Android: grantUriPermssions: temporary permission to sign.
  • The android: permission: the Provider to read and write permissions.
  • The android: readPermission: read access to the Provider.
  • Android: writePermission: write permissions of the Provider.
  • Android :enabled: indicates that the flag allows the system to start the Provider.
  • The Android: Exported: tag allows other applications to use this Provider.
  • The Android :multiProcess: flag allows the system to start the Provider in the same process that calls the client.

49. Save the Fragment state

Fragment state save entry:

1. Save the state of your Activity. Inside the Activity onSaveInstanceState() method, call FragmentManger saveAllState(). It saves the instance state and View state of each Fragment in mActive.

2, FragmentManager also provides public methods: saveFragmentInstanceState (), the individual fragments can be preserved, which is to provide for us.

3. In the FragmentManager moveToState() method, when the state falls back to ACTIVITY_CREATED, the saveFragmentViewState() method is called to save the View’s state.

50. What is the difference between creating a thread directly in an Activity versus creating a thread in a service?

Created in an Activity: the Thread serves the Activity, completes the task specified by the Activity, and actively notifies the Activity of some messages and events. After the Activity is destroyed, the Thread has no meaning to live.

Created in a Service: This is the only way to ensure that a Thread has the longest life cycle. As long as the entire Service does not exit, a Thread can be executed in the background, usually in onCreate() of the Service and in onDestroy(). Therefore, threads created in the Service are suitable for performing some background tasks independent of APP for a long time. The most common one is to maintain a long connection with the server in the Service.

51, how to calculate the size of memory occupied by a Bitmap, how to ensure that loading Bitmap does not cause memory overflow?

Bitamp Memory size = Width Pixel x (inTargetDensity) x Height Pixel x (inTargetDensity) x Memory occupied by a pixelCopy the code

Note: Here inDensity represents the DPI of the target image (under which resource folder), inTargetDensity represents the DPI of the target screen, so you can see that inDensity and inTargetDensity stretch the width and height of the Bitmap. To change the memory footprint of the Bitmap.

There are two ways to get memory footprint in a Bitmap.

GetByteCount () : API12 is added to represent the minimum amount of memory required to store Bitmap pixels. GetAllocationByteCount () : Added by API19 to represent the size of memory allocated for bitmaps in memory, replacing the getByteCount() method. GetByteCount () and getAllocationByteCount return the same result when the Bitmap is not reused. When decoding images by multiplexing bitmaps, getByteCount() represents the size of memory occupied by the newly decoded image, and getAllocationByteCount() represents the actual size of memory occupied by the multiplexed Bitmap (i.e. the length of the mBuffer).

To ensure no memory overflow during Bitmap loading, BitmapFactory can be used for image compression with the following parameters:

BitmapFactory. Options. InPreferredConfig: ARGB_8888 RGB_565 instead, change the encoding, save memory. BitmapFactory. Options. InSampleSize: scaling, can the library reference Luban, wide high calculate the appropriate scaling according to the pictures. BitmapFactory. Options. InPurgeable: can make the system out of memory when the recovery of memory.

52. What is done with the application update section? (Grayscale, forced update, regional update)

2. Compare the online versionCode with the local versionCode, and the update window pops up. 3. Download the APK file (file download)

Gray scale: (1) find a single channel to put a special version. (2) Upgrade the platform to allow some users to push upgrade notification or even upgrade the version forcibly. (3) Open a separate download portal. (4) The code of both versions is typed into the APP package, and then the test framework is implanted in the APP side to control which version is displayed. The testing framework is responsible for communicating with the API on the server side, and the server side controls the distribution of A/B version on the APP, so that A specified group of users can see version A and other users can see version B. The server side will have corresponding reports to show the number of A/B versions and the effect comparison. Finally, it can be controlled by the background of the server, and all users can switch to version A or B online

Either way, you need to do some versioning and assign special version numbers to distinguish them. Of course, since it is to do gray scale, data monitoring (conventional data, new feature data, main business data) or to do a bit, the data pile to play. Also, gray version had better have the ability to recover, is generally forced to upgrade the next official version.

Forced update: The general processing is to enter the application popup to notify the user of version update, popup can not be cancelled without the cancel button. This allows the user to update or close the app. You can also add a cancel button, but if the user chooses to cancel, the app will exit.

Incremental update: BSDIff: binary difference tool BSDIff is the corresponding patch synthesis tool, based on two different versions of binary files, generate patch files. Patch files. Use bspatch to combine old APK files with new APK files. Notice Versions are distinguished by the MD5 value of apK files.

53. Please explain why Android adds a signature mechanism.

1. Identity authentication of the sender Because the developer may confuse and replace installed programs by using the same Package Name to ensure that packages with different signatures will not be replaced.

2. Ensure the integrity of information transfer Signature processes each file in a packet to ensure that the contents of the packet are not replaced.

3. Market’s requirements on software to prevent repudiation in transactions.

54. Why can bindService be associated with an Activity life cycle?

LoadedApk records ServiceConnection information when the bindService method is executed.

LoadedApk check if there are BroadcastReceiver and ServiceConnection unregistered/unbound. If there are BroadcastReceiver and ServiceConnection unregistered/unbound, LoadedApk check if there are BroadcastReceiver and ServiceConnection unregistered/unbound. AMS will be notified to derestrate/unbind the BroadcastReceiver and Service, and an exception message will be printed to inform the user that the derestrate/unbind operation should be performed voluntarily.

How do I configure multichannel packages using Gradle?

Packages for generating different channels

Android {productFlavors {xiaomi {} Baidu {} wandoujia {} _360 {} // or "360"{}Copy the code

Execute./gradlew assembleRelease, which will type the release package for all channels;

Executing./gradlew assembleWandoujia will print the release and debug packages for the Pea pod channel;

Executing./gradlew assembleWandoujiaRelease will generate the release package for the pea pod.

BuildType and productFlavor can therefore be combined to produce different Build Variants, or combinations of types and channels.

56. How do Activty and Fragmengt communicate? How do Fragmengt and Activty communicate?

(a) Handler

(2) Broadcasting

(3) EventBus: EventBus, RxBus, Otto

(4) Interface callback

(5) Bundles and setArguments

Is custom View more efficient than XML definition? Give reasons.

Custom views are more efficient than XML definitions:

1. Less parsing XML.

2. Custom View reduces the measurement between ViewGroup and View, including parent quantum, child quantity itself, child position in the parent, when the child View changes, some of the parent’s attributes will change.

There are several kinds of broadcast registration, and what are the advantages and disadvantages?

The first is resident (static registration) : when an application is closed and a message is broadcast, the application is called by the system and runs by itself.

The second is non-resident (dynamic registration) : broadcasts follow the life of the program.

Dynamic registration

Advantages: In Android’s broadcast mechanism, dynamic registration takes precedence over static registration, so you need to register broadcast receivers dynamically if necessary.

Disadvantages: Broadcasts are disabled when the Activity used to register is turned off.

Static registration

Advantages: There is no need to worry about whether the broadcast receiver is turned off. As long as the device is on, the broadcast receiver is on.

There are generally several kinds of service startup. How to communicate with Activty and how to communicate with each other

Method:

1, startService:

onCreate()—>onStartCommand() —> onDestory()

If the service is already enabled, onCreate() is not repeated, but onStartCommand() is called. Once the service is started, it has nothing to do with the caller (the initiator). The initiator exits, the initiator hangs, and the service continues to run in the background for a long time. Openers cannot invoke methods in the service.

2, bindService:

onCreate() —>onBind()—>onunbind()—>onDestory()

Bind starts the service, binds the service, the caller hangs, the service also hangs. The binder can invoke methods within the service.

Communications:

1. Through Binder objects.

2. Use broadcast.

60, DDMS and traceView differences?

DDMS stands for davik Debug monitor service. In a nutshell, DDMS is a program execution viewer, in which you can see information such as threads and stacks, and traceView is a program performance analyzer. Traceview is part of the DDMS.

Traceview is an Android platform specific data acquisition and analysis tool, which is mainly used to analyze hotspot (bottleneck) in Android applications. Traceview itself is only a data analysis tool, and data collection needs to use the Debug class in the Android SDK or DDMS tool. The developer calls the startMethodTracing function of the Debug class in the Android SDK before the start of some critical code segment, and the stopMethodTracing function before the end of the critical code segment. During the running of these two functions, the function execution of all the application threads (note, only Java threads) during the running time will be collected, and the collected data will be saved to a file under/MNT /sdcard/. The developer then needs to analyze this data using the Traceview tool in the SDK.

The ListView is stuck

Adapter getView does not use setTag or getTag for convertView;

In the getView method, the ViewHolder assignment after initialization or the display state and background of multiple controls are not optimized, or there are complex calculations and time-consuming operations involved.

The row inflate is too deeply nested in the getView method (the layout is too complex) or because the layout has a large image or background.

Adapter Redundant or unreasonable notifySetDataChanged;

If multiple layers of nesting are unavoidable, it is recommended to set the height and width of the listView to match_parent. If the listView is inherited by code, add LayoutPrams to your inherited class. Note that the height and width are mactch_parent.

62, The role and understanding of AndroidManifest

The androidmanifest.xml file, also known as the manifest file, tells you if the application contains the component, and if so, launches it directly. It can be understood as an application configuration file.

Function:

  • Name the Java software package of the application. The software package name acts as the unique identifier of the application.
  • Describes the various components of an application, including the activities, services, broadcast receivers, and content providers that make up the application. It also names the classes that implement each component and publishes their capabilities, such as intent-messages that they can handle. These declarations tell the Android system about the components and the conditions under which they can be launched.
  • Determine the process that hosts the application component.
  • Declares what permissions an application must have to access protected parts of the API and interact with other applications. It also declares the permissions that other applications need to interact with the application component
  • List Instrumentation classes that provide analysis and other information at application runtime. These declarations will only appear in the manifest while the application is in development and will be removed before the application is released.
  • Declare the minimum Android API level required by your application
  • Lists the libraries that your application must link to

63. LaunchMode application scenario

Standard, create a new Activity.

SingleTop, which is not an Activity of this type at the top of the stack, creates a new Activity. Otherwise, onNewIntent.

SingleTask, unstack no Activity of this type, create Activity, otherwise, onNewIntent+ClearTop.

Note:

When an Activity is launched in “singleTask” mode, it first looks for tasks with affinity equal to its taskAffinity value in the system. If such a Task exists, it will start in that Task, otherwise it will start in a new Task stack. Therefore, if we want an Activity with a “singleTask” launch mode to start in a new task, we need to set a separate taskAffinity property value for it.

If the “singleTask” mode is not used to start an Activity in a new task, it checks to see if an instance of the Activity already exists in the existing task. If so, it terminates all activities on that instance. That is, the Activity instance ends up at the top of the Stack of tasks.

There is only one “singleTask” Activity in a task stack. It can have other activities on it. This is different from singleInstance.

SingleInstance, there’s only one Activity in the rollback stack, no other activities.

SingleTop is suitable for receiving notifications to launch the content display page.

For example, the news content page of a news client, if you receive 10 news feeds, it is annoying to open the news content page one at a time.

SingleTask is suitable as a program entry point.

For example, the home screen of a browser. No matter how many apps you launch the browser from, it only launches the home screen once, otherwise it goes to onNewIntent and clears the other pages above the home screen.

SingleInstance application scenarios:

Alarm screen. You used to set an alarm: 6 a.m. At 5:58 a.m., you activate the alarm Settings screen and press the Home button to return to the desktop. At 5:59 am, you are chatting with your friends on wechat; At 6 o ‘clock, the alarm goes off and a dialog Activity(called AlarmAlertActivity) pops up indicating that it’s 6 o ‘clock (the Activity is launched in SingleInstance loading mode), you press the back button, This is because the Task on which AlarmAlertActivity is located has only one element in its stack, so the stack of this Task is empty after exiting. If AlarmAlertActivity is started as a SingleTask, pressing the back button should take you to the alarm setting screen when the alarm goes off.

64, Describe the relationship between an Activity, an Intent, and a Service

They are among the most frequently used classes in Android development. Activity and Service are one of the four components of Android. They’re both subclasses of ContextWrapper, so they’re kind of brothers. However, the two brothers have their own skills. Activity handles the display and interaction of the user interface, while Service handles the processing of background tasks. An Activity and a Service can pass data between them through an Intent, so you can think of an Intent as a messenger.

The difference between ApplicationContext and ActivityContext

These are two different contexts, and they’re the two most common ones. In the first case, the lifecycle of the context is related to the lifecycle of the Application. The context is destroyed as the Application is destroyed, for the lifetime of the Application, regardless of the lifecycle of the activity. The second context is related to the Activity lifecycle, but for an Application, the Activity can be destroyed several times, so the context belonging to the Activity will be destroyed multiple times. Which context to use depends on the application scenario. When using context, be careful of memory leaks. Note the following:

  • Do not let an object with a long lifetime refer to the Activity context; that is, make sure that the object referring to the Activity has the same lifetime as the activity itself.
  • For objects with a long lifetime, you can use an Application Context.
  • Avoid non-static inner classes. Use static classes to avoid life cycle problems and pay attention to life cycle changes caused by internal class references to external objects.

The difference between Handler, Thread, and HandlerThread

1. Handler: In Android, it is responsible for sending and processing messages. It can be used to communicate messages between other branch threads and the main thread.

Thread: the smallest unit of execution in a Java process, which is the basic unit for executing processor scheduling. A program that runs alone in a process.

3, HandlerThread: A HandlerThread class inherits from Thread. Android does not encapsulate any Java threads. Instead, it provides a HandlerThread class inheriting from Thread. HandlerThread descends from Thread, so it is essentially a Thread. Thread differs from Thread in that it implements Looper internally, which is essential for the Handler messaging mechanism. Having our own Looper allows us to distribute and process messages in our own threads. If HandlerThread is not used, the looper.prepare () and looper.loop () methods need to be called manually.

67. Principles of ThreadLocal

ThreadLocal is a class that creates thread-local variables. The usage scenarios are as follows:

  • Implement single thread singleton and single thread context information storage, such as transaction ID, etc.

  • To make threadsafe, non-thread-safe objects become thread-safe when ThreadLocal is used, since each thread has a corresponding instance.

Carry some thread-specific data to avoid passing parameters back and forth in a method.

When multithreading is needed, there is a variable that does not need to be shared, so there is no need to use the troublesome keyword synchronized to lock it. Each thread is equivalent to opening up a space in the heap memory, and the thread has a buffer for shared variables, through which the shared variables in the heap memory can be read and manipulated. A ThreadLocal is equivalent to memory within a thread, a local variable. The thread itself can be read and manipulated each time, without having to interact with variables in main memory through buffers. Synchronized does not modify data in main memory and then copy data from main memory to working memory in a thread. ThreadLocal allows threads to monopolize resources and store them internally, preventing threads from blocking and causing CPU throughput to drop.

Each Thread contains a ThreadLocalMap. The key of the ThreadLocalMap is the object of the ThreadLocal, and the value of the ThreadLocalMap is the exclusive data.

Calculate the nesting hierarchy of a view

private int getParents(ViewParents view){ if(view.getParents() == null) return 0; } else { return (1 + getParents(view.getParents)); }}Copy the code

MVP, MVVM, MVC explanation and practice

MVC:
  • The View layer (View)

Corresponds to the XML layout file and the Java code dynamic View section

  • Control layer (Controller)

The Android control layer in MVC is assumed by the Activity. The Activity was originally used as an initialization page to display data operations, but because the XML view function is too weak, so the Activity has to be responsible for both the display of the view and the addition of control logic, which assumes too many functions.

  • The Model layer (the Model)

For business model, establish data structure and related classes, it is mainly responsible for network request, database processing, I/O operations.

conclusion

The model is completely decoupled. Controller and View are not decoupled. The interaction between layer and layer should be completed by callback or message mechanism, and the controller and View cannot be completely separated in Android. However, at the level of code logic, it must be noted that the business logic is placed in the Model layer, which can be better reused and modified to increase business.

MVP

By introducing the interface BaseView, let the corresponding View components such as Activity and Fragment to realize BaseView, realize the independence of View layer, and realize the complete decoupling of Model and View through the middle layer Preseter. MVP completely solved the problem of confusing View and Controller in MVC, but with the increase of business logic, a page may be very complex, the UI changes are very many, there will be a lot of cases, so that the View interface will be very large.

MVVM

As mentioned in MVP, as the business logic increases and the UI changes a lot, there will be a lot of UI-related cases, which will cause the View interface to be very large. And MVVM solves this problem, through the mechanism of bidirectional binding, the realization of data and UI content, as long as you want to change one side, the other side can update a design concept, which saves a lot of cases in the View layer, just need to change the data on the line.

MVVM in relation to DataBinding?

MVVM is an idea, and DataBinding is Google’s handy tool for implementing MVVM.

MVVM seems to solve the MVC and MVP problems well, but due to the two-way binding of data and view, it is not easy to locate the source of problems, either caused by data problems or the modification of view attributes in the business logic. If you plan to use MVVM in your project, consider using the official architecture components ViewModel, LiveData, and DataBinding to implement MVVM.

How to choose the three?
  • If the project is simple, with little complexity and little future change, then don’t use design patterns or architectural methods. Just encapsulate each module and make it easy to call. Don’t use design patterns or architectural methods for the sake of using them.
  • For show-oriented APPS, most of the business logic is in the back end. The main function of the APP is to display data and interact with others. Therefore, MVVM is recommended.
  • For utility classes or apps that need to write a lot of business logic, use MVP or MVVM.

What is the difference between apply and commit for SharedPrefrences

The difference between these two approaches is:

  1. Apply returns no value and commit returns Boolean indicating whether the change was committed successfully.

  2. Apply commits modified data atoms to memory and then asynchronously commits them to hardware disks, whereas commit synchronously commits to hardware disks. Therefore, when multiple concurrent commits are committed, they wait for the ongoing commit to be saved to disk before operating, thus reducing efficiency. However, apply is only atomic commits to content, and subsequent functions that call Apply will directly overwrite the previous memory data, thus improving efficiency to a certain extent.

  3. The Apply method does not prompt for any failures.

Since sharedPreference is a single instance in a process, concurrency conflicts generally do not occur. If you do not care about the result of the submission, it is recommended to use Apply. Of course, if you need to ensure the successful submission and subsequent operations, you still need to use COMMIT.

Are Base64 and MD5 encryption methods?

What is Base64?

Base64 is a text-based binary encoding that uses four bytes of text to represent three bytes of raw binary data. It converts binary data into A sequence of 64 printable characters: A-zA-Z0-9 +/

What is MD5?

MD5 is a hash algorithm that can generate a 128-bit (16-byte) hash value from any data to ensure the integrity and consistency of information transmission. We often use MD5 in the registration and login module, and the user password can be stored in MD5 encryption mode. Such as: md5 (hello world, 32) = 5 eb63bbbe01eeed093cb22bb8f5acdc3

Encryption is when the data is converted into a different format, and no one can convert it back except the person who got the decryption method. MD5 is a message digest algorithm. It is irreversible and cannot be decrypted. So it’s a one-way encryption algorithm. Base64 is not an encryption algorithm, it is a data encoding method, although reversible, but its encoding method is open, there is no encryption.

What is the difference between HttpClient and HttpConnection?

The Http Client is suitable for Web browsers. It has a large number of flexible apis, which are stable to implement and rich in functions. It provides many tools to encapsulate Http request headers, parameters, content bodies, and responses. However, because of this, its large API makes it difficult to improve without breaking compatibility, so the Android team is not keen to modify and optimize the Apache Http Client. (And ditched the Http Client in Android 6.0, replacing it with OkHttp)

HttpURLConnection has wrapped up most of the functionality, making the Http Client’s advanced functionality more complex. In addition, HttpURLConnection has added some Https improvements in Android 2.3 (including the Http Client, Both support HTTPS). Response Cache is added in Android 4.0. When caching is installed (calling the HttpResponseCache install() method), all HTTP requests do one of three things:

  • All cached responses are provided by local storage. Because there is no need to initiate a network connection request for a task, all responses are immediately available.
  • Contingent cached responses must be checked by the server for updates. For example, if the client makes a request like “send me the image if /foo. PNG has changed”, the server needs to return the updated data or a 304 Not Modified status. If the requested content does not happen, the client will not download any data.
  • Responses that are not cached are provided directly by the server. This part of the response is later stored in the response cache.

Prior to Android 2.2, HttpClient was less buggy, so using it was the best choice. For Android 2.3 and later, HttpURLConnection is the best choice. Its simple API and small size make it ideal for Android projects. The compression and caching mechanisms can effectively reduce network access traffic, improve speed and save power. HttpURLConnection should be preferred for new applications, as the Android authorities will spend more time optimizing HttpURLConnection in the future.

73, ActivityA jumps to ActivityB, and then B returns to A by back, the respective lifecycle order, A and B are opaque.

ActivityA jump to ActivityB:
Activity A: onPause Activity B: onCreate Activity B: onStart Activity B: onResume Activity A: onStopCopy the code
ActivityB returns ActivityA:
Activity B: onPause Activity A: onRestart Activity A: onStart Activity A: onResume Activity B: onStop Activity B: onDestroyCopy the code

How to intercept and abort a short message through broadcast?

This signal can be monitored, and when passed to the real receiver program, we will customize the broadcast receiver program priority is greater than it, and cancel the broadcast propagation, so that the SMS interception function can be realized.

75, What is the difference between BroadcastReceiver and LocalBroadcastReceiver?

1. Application scenarios

1. BroadcastReceiver is used to transmit messages between applications.

2. LocalBroadcastManager is more efficient than broadcastReceiver for delivering messages inside applications.

2, security,

1. BroadcastReceiver uses the Content API, so it is essentially cross-app and therefore must not be abused by other applications.

2. LocalBroadcastManager doesn’t need to worry about security because it only works within applications.

3. Principle

(1) Different from BroadcastReceiver, which is implemented with Binder communication mode as the underlying mechanism, the core implementation of LocalBroadcastManager is actually Handler, which only uses the Match function of IntentFilter. It doesn’t matter if the BroadcastReceiver is a different interface, just leveraging existing classes and concepts.

(2) LocalBroadcastManager, as an application communication implemented by Handler, has better security and higher efficiency.

How to choose a third party, consider from those aspects?

General direction: make judgment from software environment

Performance is the number one problem open source software addresses.

A good ecosystem is a prerequisite for a good open source library, and the criteria are to see if it is constantly updated and able to handle the questions raised by github users. Is there an active discussion in the community about this open source library?

Background, who launched the open source library, which company launched it.

The number of users and what well-known enterprises landing use

Small direction: Judge from the perspective of the software developer

Whether it solves our existing problems or maintenance costs in the long term.

How many people in the company will.

Cost of learning.

Simply say the access to the payment process, whether you have access to the payment function?

Alipay payment functions:

1. Firstly, log in to the open platform of Alipay to create an application, and add the App payment function to the application. Since the App payment function requires signing a contract, you need to upload company information, certificates and other materials to sign a contract.

2. Configure the key after the contract is signed. Use the tool provided by Alipay to generate RSA public key and private key. The public key needs to be set in the management background.

3. The android studio integration

(1) Copy jar package; (2) Initiate and process payment requests.Copy the code

78, singleton thread synchronization requirements:

1. The singleton class ensures that it has only one instance (constructors are private: they are not instantiated externally, nor inherited).

2. A singleton class must create its own instance.

3. A singleton class must provide a unique instance of another object.

79. How to ensure that Service is not killed?

The Android process is deathless in three ways:

A. Provide process priority to reduce the probability of process killing

Method 1: Monitor the lock screen unlocking event of the mobile phone, start the Activity with 1 pixel when the screen is locked, and destroy the Activity when the user unlocks the screen.

Method 2: Start the foreground service.

Method 3: Improve the service priority:

In the androidmanifest.xml file, you can set the highest priority for intent-filter by android:priority = “1000”. 1000 is the highest value. If the number is smaller, the priority is lower.

B. Pull the process after it is killed

Method one: register the high frequency broadcast receiver, arouse the process. For example, the network changes, unlock the screen, boot, and so on

Method two: Two processes evoke each other.

Method three: rely on system arousal.

Method 4: Restart service: service + broadcast in onDestroy. When a service goes through ondeStory, it sends a customized broadcast. When the service receives an ondeStory, it restarts the service.

C. Rely on third parties

According to different terminals, xiaomi push can be connected to Xiaomi mobile phones (including MIUI) and Huawei push can be connected to Huawei mobile phones. Other mobile phones can consider access to Tencent carrier pigeon or Aurora push and Xiaomi push to do A/B Test.

ContentProvider ContentResolver ContentProvider ContentObserver

ContentProvider: Manages data and provides operations of adding, deleting, modifying, and querying data. Data sources can be databases, files, XML, and networks. ContentProvider provides a unified interface for accessing these data and can be used to share data between processes.

ContentResolver: A ContentResolver can manipulate data in different ContentProviders for different URIs, and external processes can interact with the ContentProvider through the ContentResolver.

ContentObserver: Watches data changes in ContentProvider and notifies the outside world of the changes.

How to import external database?

Include the original database in the project source code in RES/RAW.

Under Android system, the database should be stored in /data/data/com. (package name)/directory, so what we need to do is to pass the existing database into that directory. To do this, use FileInputStream to read from the original database, and use FileOutputStream to write the read to that directory.

82, LinearLayout, FrameLayout, RelativeLayout performance comparison, why?

A LinearLayout with a weight will call its child onMeasure twice

A child View with a RelativeLayout whose height is different from that of a RelativeLayout can cause efficiency problems, especially when the child View is complex. If possible, use padding instead of margin.

Use LinearLayout and FrameLayout instead of RelativeLayout without compromising the depth of the hierarchy.

Why does Google create a new RelativeLayout for developers by default, but use a LinearLayout in a DecorView?

Because the depth of the DecorView hierarchy is known and fixed, a title bar at the top and a content bar at the bottom. Using a RelativeLayout does not reduce the depth of the hierarchy, so using a LinearLayout on the root node is most efficient at this point. By default, a new RelativeLayout is designed to maximize performance by using as few View hierarchies as possible, since complex View nesting can have a greater impact on performance.

83. Scheme jump protocol

Scheme in Android is an in-page jump protocol. You can jump to each page in app by defining your own Scheme protocol

The server can customize to tell the APP which page to jump to

App can jump to another App page

You can switch to the H5 page

84, HandlerThread

1. HandlerThread principle

When multiple time-consuming tasks need to be executed in the system, each task starts a new thread to execute the time-consuming tasks. As a result, the system creates and destroys threads for many times, affecting the system performance. To solve this problem, Google came up with HandlerThread, which is essentially a Thread class that inherits threads. HandlerThread has its own internal Looper object for loopr loops. Asynchronous tasks can be performed in the handleMessage() method by passing the Looper object of the HandlerThread to the Handler object. To create a HandlerThread, the handlerThread.start () method must be called. The Thread will first call the run method to create a Looper object. When time-consuming tasks enter the queue, you do not need to start a new thread. Instead, you can execute time-consuming tasks in the original thread. Otherwise, the thread is blocked. One specific use scenario for this in Android is IntentService. Because the Run () method of a HanlderThread is an infinite loop, you can terminate the HandlerThread with its quit or quitSafely method when it is clear that the HandlerThread is no longer needed.

2. Advantages and disadvantages of HanlderThread

  • The advantage of HandlerThread is that asynchrony does not clog, reducing the performance cost.

  • The disadvantage of HandlerThread is that it cannot continue multi-task processing at the same time and has to wait for processing, which is inefficient.

  • Unlike a thread pool, HandlerThread is a string queue with only one thread behind it.

85, IntentService

IntentService is a special kind of Service that inherits from Service and is an abstract class, so you must create a subclass of it to use IntentService.

The principle of

Implementatively, IntentService encapsulates HandlerThread and Handler. When IntentService is first started, its onCreate() method is called, onCreat() creates a HandlerThread, and then uses its Looper to construct a Handler object, mServiceHandler, Messages sent through the mServiceHandler will eventually be executed in the HandlerThread.

Generate a default worker thread independent of the main thread to execute all Intetnt passed to the onStartCommand() method.

Create a work queue to deliver an Intent object to onHandleIntent(), one at a time, so you don’t have to worry about multithreading. The service is stopped automatically after all intents have been executed, so you don’t need to call the stopSelf() method to stop.

The service provides a default implementation of the onBind() method, which returns NULL.

Provides a default implementation of the onStartCommand() method, which delivers an Intent to a work queue and then fetches it one at a time from the work queue to the onHandleIntent() method, where the Intent is handled accordingly.

Why use stopSelf() after executing onHandlerIntent() in the handleMessage() callback of mServiceHandler?

Because the stopSel() method stops the service immediately, and stopSelf (int startId) waits for all messages to be processed before terminating the service. In general, StopSelf (int startId) Determines whether the number of times the service has been started recently is the same as that of startId. If the number is the same, the service is stopped immediately. If the number is not the same, the service is not stopped.

How to set an Activity to look like a window.

In the configuration:

android:theme="@android:style/Theme.Dialog"
Copy the code

In addition

android:theme="@android:style/Theme.Translucnt"
Copy the code

Yes Set transparency.

87, Several ways to communicate across processes in Android

1: Access activities of other applications, such as calling system calling applications

Intent callIntent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:12345678");
startActivity(callIntent);
Copy the code

2: Content Provider For accessing system albums

3: Broadcast, such as displaying the system time

4: AIDL service

Intents are different from implicit intents

Intents that explicitly specify the name of the target component are called “explicit intents.”

Intents that do not specify the name of the target component are called “implicit Intents.”

For implicit intents, specify an intent-filter when defining an Activity. When an implicit intent object is matched by an intent filter, three aspects are referenced:

Action (Action)

Category [‘kætɪg(ə)rɪ]

Data (Data)

<activity android:name=".MainActivity"  android:label="@string/app_name">
            <intent-filter>
                <action android:name="com.wpc.test" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="image/gif"/>
            </intent-filter>
</activity>
Copy the code

Android Holo theme and MD theme concept, and your opinion

Holo Theme

The Holo Theme is the most basic rendering method in Android Design. Since it is the most basic form of Android Design rendering, every Android 4.X mobile system has controls that integrate the Holo Theme, meaning that developers do not need to Design their own controls, but call the corresponding controls directly from the system. There are no highlights in the UI, and the Settings/phone visuals on Android 4.x are extremely consistent. The benefits of this are obvious: the app is very recognizable as an Android app and is completely impossible to clash with the system style.

Material Design

Material Design is actually a simple design language, which includes system interface style, interaction, UI, more focus on simulation, more bold and rich color use, richer interaction forms, more flexible layout forms

1. Distinct and vivid interface style

2. Color matching makes the app look bold, full of color, and highlights the content

3.Material Design attaches great importance to the layout of the interface

Responsive interaction is adopted. Such interaction design can elevate an application from simply displaying the information requested by the user to a tool that can generate more intense and specific interaction with the user.

90. How do I make the program start automatically?

Define a Braodcastreceiver, whose action is BOOT — COMPLETE, and start the program upon receiving a broadcast.

91, The Fragment life cycle in a ViewPager. The Fragment life cycle changes when sliding a page in a ViewPager.

How to view SP and SQList files in the simulator? How to visually view the number of nesting layers of a layout and load time.

93. Process and review time of packaging and launching on major platforms, and frequently asked questions (3-4 in mainstream application markets)

94. What are the processing skills for screen adaptation?

First, why should adapt

In order to ensure that users get a consistent user experience effect, make a certain element in Android phones with different sizes, different resolutions, different systems have the same display effect, to maintain the same effect on the interface, we need to adapt to various mobile phone screens!

  • Fragmentation of Android system: Based on Google’s native system, MIUI customized by Xiaomi, Flyme customized by Meizu, EMUI customized by Huawei, etc.
  • Fragmentation of Android models’ screen sizes: 5 inches, 5.5 inches, 6 inches, etc.
  • Android screen resolution fragmentation: 320×480, 480×800, 720×1280, 1080×1920, etc.
2. Basic concepts
  • Pixel (PX) : Pixel is the smallest unit of mobile phone screen, px = 1 pixel point under normal conditions, UI designers will use PX as the unified unit of measurement in their design drawings.
  • Resolution: The sum of horizontal and vertical pixel points of a mobile phone is generally described as width * height, that is, the number of horizontal pixels * the number of vertical pixels (such as 1080 x 1920), in the unit of px.
  • Screen size: The physical diagonal size of the phone. Common sizes are 4.7 inches, 5 inches, 5.5 inches, and 6 inches.
  • Screen pixel density (DPI) : points of pixels per inch. For example, if there are 160 pixels per inch, the pixel density is 160dpi (dots per inch).
  • Standard screen Pixel density (MDPI) : There are also 160 pixels per inch (160dPI), known as the standard screen pixel density (MDPI).
  • Density independent pixel (DP) : independent of the actual physical pixels on the terminal, which can ensure the same effect on devices with different screen pixel densities. It is an Android length unit. Conversion of DP to PX: 1dp = (Dpi / 160) * 1px.
  • Independent proportional pixel (SP) : dedicated font size unit This unit is used to set the font size during Android development. 12SP, 14sp, 18sp, and 22sp are recommended as font sizes.
Three, adaptation scheme

The most suitable resolution is 1280720,19201080,800*480.

Solution:

For Android screen adaptation, I think we can do it from the following four aspects:

1. Layout component adaptation

  • Be sure to specify dimensions using density-independent pixel DP or independent proportional pixel SP units.
  • Use relative or linear layouts, not absolute ones
  • Use wrap_content, match_parent, weights
  • Use attributes such as minWidth, minHeight, and lines

Dimens use:

Different values can be defined for different screen sizes, or we can define different values for different languages, because the translated length is generally not the same as the Chinese length. In addition, you can constrain layouts using percentage layouts or new features in AndroidStudio2.2.

2, layout adaptation

Use qualifiers (screen density qualifier, size qualifier, minimum width qualifier, layout alias, screen orientation qualifier) to load the appropriate UI layout based on the screen configuration.

3. Picture resource adaptation

Use automatic stretch image.9png image format to make image resources adapt to screen size.

Common images and ICONS:

It is suggested to cut the map according to the official density type, but generally we only need the cut map of XXHDPI or XXXHDPI to meet our needs;

4. Code adaptation:

Use the API provided by Google in the code to measure the screen width of the device, and then set it as required.

5. Interface coordination:

Determine the mobile phone resolution or pixel density before loading the image locally and request the corresponding level image from the server.

95, breakpoint continuation implementation?

SetRequestProperty (“Range”,”bytes= startindex-endIndex “); setRequestProperty(“Range”,”bytes= startindex-endIndex “); Method tells the server where data starts and ends. While writing to a local file, RandomAccessFile’s seek() method also supports writing anywhere in the file. Finally, the progress of the child thread is told to the Activity’s progress bar via a broadcast or event bus mechanism. The HTTP status code for disconnected continuations is 206, httpstatus.sc_partial_content.

In 96,What problems did you encounter during the project and how did you solve them?

In 97,The life cycle of an Activity in normal and abnormal cases

In 98,The usage scenarios of < include >< Merge >< stub >

In 99,What are the new container classes that Android has optimized for HashMap?

The public,

My public number JsonChao opened, if you want the first time to get the latest articles and the latest dynamics, welcome to scan attention ~

appreciates

If this library is of great help to you, you are willing to support the further development of this project and the ongoing maintenance of this project. You can scan the QR code below and get me a cup of coffee or beer. Your donation is greatly appreciated. Thank you very much!



Contanct Me

● wechat && wechat Group:

Welcome to follow me on wechat: BCCe5360. Because the number of wechat group is too many to invite two-dimensional code, so trouble you want to enter the wechat group friends, add my wechat pull you into the group (PS: the learning atmosphere and benefits of wechat group will be beyond your imagination).

Low QQ group:

2 thousand people QQ group, Awesome-Android learning exchange group, QQ group number: 959936182, welcome to join ~

About me

  • Email: [email protected]

  • Blog: jsonchao.github.io/

  • The nuggets:Juejin. Cn/user / 431853…

Thank you for reading this article and I hope you can share it with your friends or technical group, it means a lot to me.