How to Interview line by Internet companies? Please master these!

1. How to import external databases?

The original source database included in the project's res / raw

The database system should be stored in android / data / data / com.

Under (package name) / directory, so we need to do is to pass the existing database directory. To do is to read the original database using FileInputStream, FileOutputStream to write and then read something into that directory.

2. Local broadcasting and global broadcast what is the difference?

Due to broadcast data dissemination in the context of this application, do not worry about the privacy of data leakage.
Do not worry about anything else with forged broadcast, pose a safety hazard.
Compared global broadcast transmission within the system, it is more efficient.

What 3.intentService role, AIDL to solve the problem - Millet

Generates a default main thread and the worker threads independent of each other to execute all requests to Intetnt onStartCommand () method.

Generate a work queue to send the Intent object to your onHandleIntent () method, the same time to transmit only an Intent object, so that you do not have to worry about multi-threading problems. In all requests (Intent) are automatically stops after executing the service, so you do not need to call your own stopSelf () method to stop.

The service provides a onBind () default implementation of the method, it returns null

Providing a default onStartCommand () method is implemented, it will be transmitted first to the Intent work queue, and then takes out a transfer to onHandleIntent () method from the work queue, the corresponding processing in the process of the Intent.

AIDL (Android Interface Definition Language) is an IDL language for generating the code can be inter-process communication (interprocess communication, IPC) between two processes on Android. If a process (e.g. Activity) to call a further process (e.g.-Service) operation target, it can be used to generate serializable AIDL parameter.

AIDL IPC mechanism is an interface for, like, like COM or Corba, but lighter-weight. It uses a proxy class in the client and to transfer data to achieve the end.

4.Ubuntu compile Android - Baidu

Into the source root directory
. Build / envsetup.sh
Lunch
Full (compile all)
userdebug (select the compiled version)
the make -j8 (open 8 threads compilation)

5.LaunchMode scenarios - Baidu - Millet - music as

standard, create a new Activity.

singleTop, the stack is not the type of Activity, create a new Activity. Otherwise, onNewIntent.

singleTask, fallback stack is not the type of Activity, create Activity, otherwise, onNewIntent + ClearTop.

note:

Set "singleTask" Activity start mode, when it starts, it will first look for property values in the system affinity equal to its property values taskAffinity of Task exist; if there is such a Task, it will start in this Task, the otherwise it will start a new task stack. Therefore, Activity if we want to set up "singleTask" start mode to start a new task, you must set up a separate taskAffinity property value for it.
If you set the time Activity "singleTask" startup mode is not the start of a new task, it checks to see whether the corresponding Activity instance already exists in the existing job, if there is, this will be located in the above example Activity All Activity end off, that is the ultimate example of this Activity will be located in the top Stack task.
There is only one Activity "singleTask" startup mode in a task stack. Above him may have other Activity. This is consistent with singleInstance there is a difference.
singleInstance, fallback stack, only this one Activity, no other Activity.

singleTop start receiving notifications for content display page.

For example, a news client news content pages, if you receive 10 news feeds, news content each time a page is opened very annoying.

singleTask suitable as a program entry point.

For example, the main interface of the browser. No matter how many applications start from the browser, it will only start once the main interface, the remaining cases will go onNewIntent, and empties the other pages of the main interface above.

singleInstance scenarios:

Alarm bell interface. Have you ever set a alarm: 6 am. At 5:58, you started the alarm setting interface, press the Home key to return to the desktop; in the 5:59 time-sharing, you chat with friends in the micro-channel; 6:00 when the alarm rang, and pop-up Activity in the form of a dialog box (called AlarmAlertActivity) prompt you to 6:00 because AlarmAlertActivity where Task (this Activity is to SingleInstance load mode is enabled), you press the return key, return to a micro-channel chat interface, which is his stack is only one element, so after you exit the Task stack empty. If you are SingleTask open AlarmAlertActivity, then when the alarm rang when should press the return key to enter the alarm setting interface.

6. Multi-threaded -360

Activity.runOnUiThread(Runnable)
View.post(Runnable),View.postDelay(Runnable,long)
Handler
AsyncTask

7.Handler, Thread and HandlerThread difference - Millet

It can be seen - (> java.lang.Object java.lang.Thread) described, Android Thread does not do any of the package of Java Thread, but Android provides a class that inherits from Thread HandlerThread (android.os from the Android Thread .HandlerThread -> java.lang.Thread), this class of Java Thread did a lot of convenience packaging Android system.

android.os.Handler can instantiate the object by Looper and run in another thread, Android provides Handler let other threads run implemented in the thread, but also on HandlerThread. HandlerThread objects which can be obtained after the start Looper objects, with the object instance Looper Handler.

8. What causes a memory leak - US group

8.1. Resource object not closed due to a memory leak

Description:
resource objects such as (Cursor, File documents, etc.) are often used some cushion, when we do not use, they should be closed in a timely manner, so that their timely recovery of buffer memory. They not only present in the buffer java virtual machine, it is also present in the outer java virtual machine. If we put it references only set to null, not close them, they tend to cause a memory leak. Because some resource objects, such as SQLiteCursor (in the destructor finalize (), if we do not close it, they will tune it to close ()), if we do not close it, the system will shut it down in the recovery of it, but such efficiency is too low. So for resource objects when not in use, it should call its close () function, which was closed off, and then only set to null. When our program exits must ensure that our resource object has been closed.
Programs often operate query the database, but there is often a complete use of the Cursor is not closed. If our query result set is relatively small, the memory consumption is not likely to be found only in the case of a normally operating time of a large number of memory will reproduce the problem, so it will bring difficulties and risks to future testing and troubleshooting.

8.2. When constructing Adapter, do not use cache convertView

Description:
to construct the ListView BaseAdapter an example, a method in the BaseAdapter:
public View the getView (int position, ViewconvertView, the ViewGroup parent)
to view each object to provide a desired item to ListView. ListView will BaseAdapter from the initial view object according to the current screen layout of a number of examples, but these will ListView view cached objects. When scrolling up ListView, view objects located at the uppermost original list item will be recovered and then used to construct the lowermost emerging list item. This configuration process is performed by the getView () method, getView () of the second parameter is to be cached convertView View of the view list item object (at initialization is not in the cache convertView view object is null). It can be seen, if we do not use convertView, but always in getView () re-instantiating a View object, then that is a waste of resources but also a waste of time, it will make the memory footprint is growing. ListView recovery process view object can view the list item:
android.widget.AbsListView.java -> voidaddScrapView (View Scrap) method.
Sample code:

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

Corrected sample 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; 
} 

8.3.Bitmap object calls recycle when not in use () to release memory

Description:
Sometimes we will manually operate a Bitmap object, if a Bitmap object comparison of total memory, when it is not being used, you can call Bitmap.recycle () method for recovering the object of pixels occupied by memory, but this is not necessary , as the case may be. You can look at the comments in the code:

/** 
•Free up the memory associated with thisbitmap's pixels, and mark the 
•bitmap as "dead", meaning itwill 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. 
*/ 

8.4. Try to use context about the application of alternative and activity-related context

This situation is a very vague memory leaks. There is a simple way to avoid memory leaks context dependent. Most notably a context is to avoid escape outside his range. Use Application context. The context of the life cycle and life cycle of your application as long, and not on the life cycle of activity. If you want to keep a long-term survival of the object, and the object requires a context, remember to use the application object. You can get by calling Context.getApplicationContext () or Activity.getApplication ()

8.5. Registration not canceled due to a memory leak

Some Android applications may refer to the object of our Anroid program (such as registration mechanism). Even our Android program has ended, but the program still has other references to an object of our Android application references a memory leak still can not be garbage. unregisterReceiver not call after call registerReceiver.

For example: Suppose we want to lock screen (LockScreen), the monitoring system of telephone service to get some information (such as signal strength, etc.), you can define a PhoneStateListener in LockScreen objects, and register it TelephonyManager service . For LockScreen object, when you need to display the lock screen interface will be created when a LockScreen objects, and when the lock screen disappear LockScreen objects will be released.

But if you forget to cancel PhoneStateListener objects before we registered at the time of release LockScreen object will result LockScreen can not be garbage. If the lock screen constantly appear and disappear, then the final due to a large number of objects LockScreen no way to be recycled and cause OutOfMemory, making system_process process hang.

Although some system program, which itself seems to be automatically canceled registration (of course not in time), but we should be clear that cancellation of registration in our program, should cancel all registrations at the end of the program.

8.6. Objects in the collection did not clean up the memory leak caused

We usually put some object reference was added to the collection when we do not need the object, and did not clean up its reference from the collection away, so this collection will grow. If this collection is static, then the situation is even more serious.

9. What music as the lead oom- - US group

1) the use of more lightweight data-structure
2) Android used inside the Enum
. 3) Bitmap object memory footprint
4) larger image
created 5) onDraw method performed inside the object
6) StringBuilder

Several ways to communicate between 10.Service and Activity

By Binder object
in the form of Broadcast (broadcast)

11. How to ensure the service is not in the background Kill

A .onStartCommand method returns START_STICKY

START_STICKY
after the service is kill the process after running onStartCommand, it will remain in the starting state, but does not retain those incoming intent. Shortly after the service will try again to re-create, as keeping the state at the start, after the call to create a service guarantee onstartCommand. If you do not pass any start command to the service, you will get to the null of intent.

START_NOT_STICKY
after the service is kill the process after running onStartCommand, and does not pass a new intent to it. Service will start out of state until a new and distinct method (startService) before re-create the call. Because if any undecided intent is not passed then the service will not start, that is, during onstartCommand not receive any null of intent.

START_REDELIVER_INTENT
after the service is kill the process after running onStartCommand, the system will start the service again, and pass a final intent to onstartCommand. Until the call stopSelf (int) stopped transfer intent. If there is good intent unprocessed after being kill, it was kill or after the service starts automatically. Therefore onstartCommand not receive any null of intent.

Second, enhance service priority

In AndroidManifest.xml file for the intent-filter by android: priority = "1000" the highest priority property, the maximum value is 1000, if the smaller the number, the lower priority, while for broadcast.

Third, to enhance the service process priority

Android is hosted in the process, when the system processes when space is tight, the recovery process will be carried out automatically in accordance with the priority. The Android process is divided into six grades, from highest to lowest priority order they are:

  • Foreground process (FOREGROUND_APP)
  • Visual process (VISIBLE_APP)
  • Secondary service process (SECONDARY_SERVER)
  • Daemon (HIDDEN_APP)
  • Content provider node (CONTENT_PROVIDER)
  • Empty process (EMPTY_APP)
    when the service is running in low-memory environments, will kill off some of the existing process. Therefore, priority will be important to the process, you can use the service startForeground into the foreground state. So that when memory is low probability of kill will be lower.

Four, onDestroy method in restart service

service + broadcast mode, that is, when the service go ondestory, and send a custom broadcast, when the broadcast is received, restart the service;

Five, Application plus Persistent property

Sixth, the state monitoring system broadcast judgment Service

Through some broadcast systems, such as: phone reboot, wake-up interface, the application status changes, etc. to monitor and capture, and then determine whether our Service still alive, do not forget to add permissions ah.

12.Android animation framework implementation principle

Animation Framework defines transparency, rotation, scaling and displacement of several common animation, and control the entire View, implementation principle is ViewGroup View where every time you view the drawing in drawChild View function to get the value of the Transformation Animation, and then call canvas.concat (transformToApply.getMatrix ()), the animation frame is completed by a matrix operation, if the animation is not completed, continue to call invalidate () function, the animation starts to drive the next drawing, the gap between the time during the animation frame is drawn function of time consumed, may cause movie consumes more CPU resources, most importantly, change the animation display only, and not the corresponding event

13.Android assigned to each application's memory size is the number - the United States Mission

android program memory is generally limited to 16M, while others 24M. In recent years, rapid development of mobile phones, usually allocate about two megabytes, and specific models related

14. Custom view Baidu optimization - music as - Millet

In order to accelerate your view, for a method called frequently, the need to minimize unnecessary code. OnDraw start with the beginning, special attention should not be here to do the memory allocation thing, because it will lead to GC, resulting in Caton. It does allocate memory during the initialization of action or animated gap. Do not do things in memory allocation when the animation being executed.

You also need to minimize the number of onDraw is called, because most of the time lead to onDraw calls invalidate (). So please try to reduce the number of calls invaildate () of. If possible, try to call invalidate contains four parameters () method is not without arguments invalidate (). will not invalidate arguments forced to redraw the entire view.

Another time-consuming operation is requested layout. Performed at any time requestLayout (), will cause the system to traverse the entire Android UI View hierarchy is calculated for each size of a view. If there is a conflict of values ​​is found, it will need to be recalculated several times. Also to keep View hierarchy is flattened, so that the efficiency is helpful.

If you have a complex UI, you should consider writing ViewGroup a custom layout to carry out his operations. With different built-in view, the view custom program may make only this part of the measurements, which avoids the view through the entire hierarchy of the calculated size. PieChart This example shows how to inherit part of ViewGroup as a custom view of. PieChart has child views, but it never measure them. But according to the law of his own layout, set directly on their size.

15.Android property animation features - music as - Millet

If you only need to move to View your demand, zoom, rotate and fade, then tween indeed have a sound enough. Clearly, however, these features are not enough to cover all scenarios once we move beyond the requirements, scale, rotate and fade in and out of these four operations on View, then tween can no longer help us busy, too that is it in terms of functionality and scalability has considerable limitations, so let's take a look tween incompetence scene.

Notice above I have described the use of such "View of the operation" introduce a motion tween between the time, yes, tween is only able to act on the View. In other words, we can for a Button, TextView, even LinearLayout, or any other components inherited from the View animation operation, but if we want to carry out a non View object animation operation, sorry, tween to help not on busy. Some friends feel can not understand how I would need for a non View object animation does it work? Here I give a simple example, say we have a custom View, there is the View in which a Point object is used to manage the coordinates, then onDraw () method which is to be drawn according to the coordinate values ​​of the Point object . That is, if we can animate the operation of the Point object, then the entire Custom View animation there. Clearly, the motion tween does not have this feature, which is its first flaw.

Then tween animation there is a defect, is the only possible move, scale, rotate and fade four animation operation, it can be if we want to dynamically change the background color View of it? Unfortunately, we can only rely on themselves to reality. To put it plainly, before inter-tween mechanism is to use hard-coded way to accomplish the functions that define these dead, basically there is no extension at all.

Finally, tween there is a fatal flaw is that it just changes the display View only, and not really to change the View property. What does that mean? For example, the upper left corner of the screen there is a button now and then we passed a motion tween to move it to the lower right corner of the screen, now you can try click on this button click event is never triggered because in practice this button or stay in the top left corner of the screen, but the motion tween will draw the button to the lower right corner of the screen only.

Three different 16.Activity Window View, fragment features -360

A craftsman like Activity (control unit), Window image window (bearing model), View grilles image (display view)
LayoutInflater like scissors, Xml configuration as grilles drawings.

Activity in calling attach, create a Window
window to create a subclass PhoneWindow, created in PhoneWindow attach the
call setContentView (R.layout.xxx) in the Activity
which is actually called the getWindow (). SetContentView ()
call setContentView PhoneWindow method of
creating ParentView: as a subclass of ViewGroup, actually DecorView (FramLayout as subclass) is created
specified R.layout.xxx filled, by filling the filler [wherein the layout refers parent DecorView]
call to ViewGroup
removeAllView call ViewGroup of (), first remove all the view out
to add a new view: addView ()
Fragment features

Fragment Activity as part of the composition of the interface occurs;
may occur simultaneously in a plurality of Fragment Activity, and may be used in a plurality of Fragment Activity; and
during operation Activity may be added, removed or replaced Fragment;
Fragment can in response to their input events, and has its own life cycle, their life cycle is affected by a host Activity life cycle.

17.View refresh mechanism - Baidu - US group

PerformTraversals ViewRoot by the object () method calls the draw () method initiates draw the View tree, it is worth noting that each time you initiate the drawing, and will not be redrawn each View tree view, but only redraw those "need to re painted "view, view class contains an internal variable dRAWN flag, when the view needs to be redrawn, the flag will be added for the view.

Call flow:

mView.draw () begin drawing, draw () method to achieve the following functions:

View draw the background
to do some preparation operation (see 5, in most cases, do not need to change the gradient box) to display the gradient box
call onDraw () method to draw the view itself (each View will need to override this method, ViewGroup do not need implementation of the method)
call dispatchDraw () method to draw the child view (view if the type is not ViewGroup, ie not contain sub-view, do not need to override this method) it is worth noting that, ViewGroup class has been rewritten dispatchDraw us () realization of the function, generally do not need to rewrite the application method, but it can override the parent class function to achieve specific functions.

Android want to learn more knowledge, or access to relevant information, please join the Android Developer exchange group: 1018342383. There are interviews finishing system resource sharing, Java language and advanced Kotlin language and related technology Android kernel, APP framework for knowledge development, 360 ° Android App all-round performance optimization. Android cutting-edge technology, advanced UI, Gradle, RxJava, applets, Hybrid, mobile architect thematic project combat aspects, React Native, and other technical tutorials! Architect courses, NDK module development, Flutter Android and other advanced technology practice all aspects of explanation. There are online Q & A

Reproduced in: https: //www.jianshu.com/p/9b8de8f3ad1d

Guess you like

Origin blog.csdn.net/weixin_33842304/article/details/91251675