Some basic knowledge of interview (Android article one)

Source: Internet
Author: User
Tags message queue

MVC pattern of androidactivity design pattern

Reference Blog, article http://www.cnblogs.com/liqw/p/4175325.html

MVC is model-view-controller

M: logical Model . Responsible for the establishment of data structure and corresponding action processing.

V: view model . Responsible for rendering the corresponding graphical information on the screen to show the user.

C: controller . Responsible for intercepting the user's keystrokes and screen touches, coordinating the model object and the View object.

The user interacts with the view, the view accepts and feeds back the user's action, the view passes the user's request to the appropriate controller, the controller decides which model to call, and the model calls the corresponding business logic to process the user request, and if the data needs to be returned, the model returns the corresponding data to the controller. The corresponding view is called by the Controller, and the returned data is eventually formatted and rendered by the view, and the returned data can be fully displayed to the user with the added user experience effect.

A model can have multiple views, a view can have multiple controllers, and a controller can have multiple models.

 
1. Model

Model is a core part of an application system and represents all the functions that the system actually implements.

For example: In a video player, the model represents a video database and the program function code that plays the video; In the photo application, the model represents a photo database, and the program function code when looking at the picture. In a telephony app, model represents a phone book, and program function code that calls and sends text messages.

The model is generated in the values directory through the XML file format, or it can be hardcoded directly into Java code. = =View and model are connected by bridge adapter. ==

2. Views (view)

View is a feedback result that the software application transmits to the user. It represents the functions of graphical display, sound playback, tactile feedback, etc. in software applications. The root node of the view is the application's own window. For example, the video player may contain the currently playing screen, which is a view. Another view component might be the text caption for the video. Another is a few play buttons, such as: Stop, Start, pause and other buttons.

The view is generated in the layout directory through an XML file format, obtained with Findviewbyid (), or directly from Java code in hard-coded ways.

3. Controllers (Controller)

Controller in the software application is responsible for the response to external events, including: keyboard percussion, screen touch, call incoming and so on. The controller implements an event queue, and each external event is uniquely identified in the event queue. The framework moves the events out of the queue and distributes them sequentially.

The most typical MVC in Android is the ListView, the data to be displayed is model, the ListView in the interface is the view, and the control data is displayed in the ListView as the controller.

Activity life cycle, startup mode

Reference book: "First line of Android code"

Android uses task stacks to manage activities, and a task is a set of activities that are stored in the stack, also known as the back stack. By default, whenever we start a new activity, he will be on the stack in the return stack and at the top of the stack. And whenever we press the back key or call the Finsh () method to destroy an activity, the activity at the top of the stack is stacked.

An activity can have up to four states in its life cycle: run state, paused state, stop state, destroy state.

The activity class defines seven callback methods that cover every aspect of the active life cycle:
1. = =OnCreate ()= =: Called when the activity is first created, completes the initialization of the activity, such as loading layouts, binding events, and so on.
2. = =OnStart ()= =: The activity is called when invisible becomes visible.
3. = =Onresume ()= =: The activity is ready to be called when the user interacts. The activity must be at the top of the stack at the back of the stack and is in a running state.
4. = =OnPause ()= =: Called when the system is ready to start or resume another activity. Typically, some of the CPU-consuming resources are freed up in this method, and some key data is saved. However, this method must be executed quickly, otherwise it will affect the use of the new stack top activity.
5. = =OnStop ()= =: Called when the activity is completely invisible.
6. = =OnDestroy ()= =: The activity is called before it is destroyed and the state of the activity becomes destroyed.
7. = =Onrestart ()= =: The activity is called before the stop state becomes a running state, that is, the activity is restarted.

the active start-up mode is divided into four kinds: standard,singletop,singletask,singleinstance.

You can set up a corresponding startup mode for your activity according to your actual needs, so you can avoid creating a large number of repetitive activity issues.

To set the activity's startup mode, simply set the Android:launchmode property on the corresponding tag in the Androidmanifest.xml, for example:

<activity      android:name=".A1"      android:launchMode="standard" />  

==standard==:

Default mode, no write configuration. The system does not care if the activity is already present in the return stack, and a new instance is created each time it is started. Therefore, in standard mode, you can have multiple identical instances, and also allow multiple identical activity overlays. When exiting, press back to exit sequentially.

==singletop==:

There can be multiple instances, but multiple activity overlays are not allowed. That is, if the activity is at the top of the stack, initiating the same activity does not create a new instance, but calls its Onnewinstant method.

==singletask==:

There is only one instance. When you launch him in the same application, if the activity does not exist, a new instance is created in the current task and, if present, the other activity on top of the task is destroy off and the Onnewinstant method is called.

==singleinstance==:

Enabling a new return stack to manage this activity, regardless of which application accesses the activity, shares the same return stack, which resolves the issue of shared activity instances. That is, there is only one instance, and this instance runs independently in a task, and this task is the only instance that does not allow any other activity to exist.

Example: There are active a,b,c, set B to singleinstance, open a->b->c sequentially, and then exit. The order is c->a->b. The principle is simple, because a,c is stored in the same return stack, in C exits directly to a, in a to exit the stack empty. Jumps to the return stack of B to continue exiting.

Click event Delivery Dispatch,intercept,ontouchevent

Reference articles, blogs: http://blog.csdn.net/morgan_xww/article/details/9372285/
Http://www.cnblogs.com/lwbqqyumidi/p/3500997.html

3 methods related to touch events:

publicbooleandispatchTouchEvent(MotionEvent ev);    //用来分派eventpublicbooleanonInterceptTouchEvent//用来拦截eventpublicbooleanonTouchEvent(MotionEvent ev);          //用来处理event

Event Distribution: Public boolean dispatchtouchevent (motionevent ev)

When a supervisor hears an event, it is first captured by the activity and enters the event distribution processing process.

If event distribution returns TRUE, the Change event is no longer distributed at this level and is already consumed in the event distribution itself. At this point, the incident has ended.

If the event distribution returns false, the event is no longer being distributed at this level and is being consumed by the Ontouchevent method of the upper control.

Event Interception: Public boolean onintercepttouchevent (motionevent ev)

If Onintercepttouchevent returns True, the event is intercepted and the intercepted event is referred to the ontouchevent of the layer control;

If the returned result is false, the event is not intercepted and the event is successfully distributed to the child view. and processed by the dispatchtouchevent of the child view.

If the super.onintercepttouchevent (EV) is returned, the event is not intercepted by default and is processed by the dispatchtouchevent of the child view.

Event Response: Public boolean ontouchevent (motionevent ev)

If Ontouchevent returns True, the event is consumed after the ontouchevent has finished processing the event. At the end of the event, no subsequent bubbling will take place.

If Ontouchevent returns false, the event continues to bubble to the upper view and is processed by the ontouchevent of the upper view after processing in ontouchevent.

If Super.ontouchevent (EV) is returned, the default processing logic is the same as the return false.

Service, two startup modes and features, how to communicate with activity

Reference Blog, article: Http://www.jianshu.com/p/2fb6eb14fdec

= = Use start to start the service = =

Steps:

    1. To define a class to inherit a service
    2. Configure the service in the Manifest.xml file
    3. Start with the StartService (Intent) method of the context
    4. Call the StopService (Intent) method to stop when it is no longer in use

The life cycle of a service started with this start is as follows:

OnCreate ()->onstartcommand () (OnStart () method Obsolete), Ondestory ()

Description: If the service is turned on, the OnCreate () will not be executed repeatedly, but the onstart () and Onstartcommand () are called.

Call Ondestory () when the service is stopped. The service will only be stopped once.

Features: Once the service is open and the caller (opener) has no relationship.
The opener exits, the opener hangs, the service is still running in the background for a long time.
The opener cannot invoke the method inside the service.

= = Use bind to open the service = =

Steps:

    1. To define a class to inherit a service
    2. Configure the service in the Manifest.xml file
    3. Start with the Bindservice (Intent, serviceconnection, int) method of the context
    4. Call the Unbindservice (Serviceconnection) method to stop when it is no longer in use

The life cycle of a service started with this start is as follows:

OnCreate ()->onstartcommand () (OnStart () method Obsolete), Ondestory ()

Description: If the service is turned on, the OnCreate () will not be executed repeatedly, but the onstart () and Onstartcommand () are called.

Call Ondestory () when the service is stopped. The service will only be stopped once.

Features: Once the service is open and the caller (opener) has no relationship.
The opener exits, the opener hangs, the service is still running in the background for a long time.
The opener cannot invoke the method inside the service.

Handler-looper-messagequeue,asynctask principle Related

Reference: The first line of code Guo Lin

Reference: http://www.cnblogs.com/devinzhang/archive/2012/02/13/2350070.html

Because Android does not allow UI operations in child threads because the UI is thread insecure, if you want to update the UI you must do it in the main thread, otherwise it will be an exception. Android provides a set of asynchronous message processing mechanisms that perfectly address the problem of UI manipulation in child threads.

Asynchronous message processing in Android consists of four parts: message, Handler, MessageQueue, and Looper.

Message:
The message is an intra-thread transmission of messages that can carry a small amount of information inside to exchange data between different threads. For example, what field, Arg1, arg2 with some integer data, and the obj field carries a single Object object.

Handler
Handler as the name implies is the meaning of the processor, it is mainly used to send and process messages, send messages generally use the handler SendMessage () method, and the message sent through a series of processing, Will eventually be passed to Handler's Handlemessage () method.

MessageQueue
MessageQueue is the meaning of Message Queuing, which is primarily used to store all messages sent through handler. This part of the message will remain in the message queue and wait for it to be processed. Each thread has only one MessageQueue object.

Looper
Looper is the steward of the MessageQueue in each thread, and after calling the Looper loop () method, it enters an infinite loop, and then every discovery of a message in MessageQueue, it is removed, And passed to Handler's Handlemessage () method. Each thread also has only one Looper object.

= = Asynchronous Message processing Flow: = =
1. Create a handler object in the main thread and override the Handlemessage () method
2. When a child thread needs a UI action, create a Message object and send the message through Handler.sendmessage ()
3. This message is added to the queue of MessageQueue waiting to be processed
4. Looper has tried to present pending messages from the MessageQueue, distributing the Handlemessage () method handler.

= =Asynctask:= =

Asynctask is an Android-provided lightweight asynchronous class that can be inherited directly. Its implementation principle is based on the asynchronous message processing mechanism, but Android helped us to do a very good package.

Since Asynctask is an abstract class, to use must be to create a subclass to inherit him, and provide three generic parameters, while overloading several methods:

Asynctask defines three types of generic type params,progress and result

    • Params: Parameters that need to be passed in to execute Asynctask, which can be used in background tasks (parameter types of the Doinbackground method), such as the URL of an HTTP request
    • Progress: When a background task executes, specify the progress type if you need to display the current progress on the interface
    • Result: The return type of the background task

Example: One of the simplest custom asynctask:

class DownloadTask extends AsyncTask<void,Integer,Boolean>{}//Params为void,表示在执行AsyncTask的时候不需要传入参数给后台任务//Progress为Integer,表示用整型数据来作为进度显示单位//Result为Boolean,表示使用布尔型数据来反馈执行结果

The current custom Downloadtask is still an empty task, and several methods in the Asynctask need to be rewritten to complete the customization of the task.

Students who have used Asynctask know that an asynchronous load of data must be overridden by the following two methods:

    • Doinbackground (Params ...): all the code for this method will run in the background sub-thread, and the more time-consuming operations can be placed here. Once the task is complete, the return statement can be used to return the execution result of the task (the returned type is the third generic parameter given at the outset). Note that you cannot manipulate the UI directly here. Publicprogress (Progress ...) can be called during execution To update the progress of the task.
    • OnPostExecute (Result):
      This method is called when the background task finishes executing and returns through the return statement. The returned data is passed as a parameter to this method, which is equivalent to how handler handles the UI. You can use the returned data for some UI operations. This method is executed on the main thread, and the result of the task execution is returned as a parameter to this method

You also have to rewrite these three methods, if necessary, but not necessarily:

    • OnPreExecute () here is the interface when the end user calls Excute, and the progress dialog can be displayed here before the task executes before calling this method.
    • onprogressupdate (Progress ...) When Publicprogress (Progress ...) is called in a background task method, this method will be called soon. You can use the progress bar to increase user experience. This method executes on the main thread and is used to show the progress of the task execution.
    • oncancelled () the action to be made when the user calls Cancel

Limitations of Asynctask

The advantage of Asynctask is that it is easy to update the UI after performing a background task, but there are many limitations to using it. To throw away the memory leak problem, the following limitations are mainly used in Asynctask:

    • Before the Android 4.1 version, the Asynctask class must be loaded in the main thread, which means that the first access to the Asynctask class must occur in the main thread;
    • This limitation does not exist on Android 4.1 and above because the main method of Activitythread (which represents the main thread) is automatically loaded Asynctask
    • The Asynctask object must be created in the main thread
    • The Execute method of the Asynctask object must be called in the main thread
    • A Asynctask object can only be called once by the Execute method

A simple example to see: http://www.cnblogs.com/absfree/p/5357678.html

Animation related

First, drawable Animation

The so-called frame animation, frame animation. An animated effect by specifying the picture and playback time of each frame to be played in an orderly manner. can be interpreted as multiple pictures to play, the picture can not be too large.

Second, View Animation

View animations, also known as tweened animations, tween animations. By specifying the initial state of the view, the time of change, the way, through a series of algorithms to transform the graphics, so as to form an animation effect, mainly alpha, scale, Translate, rotate four kinds of effects. Note: just animating in the view layer does not really change the view's properties. The actual position of the view or the position before the move

Third, Property Animation

Property animation, by constantly changing the properties of the view, constantly redraw to form an animation effect. Compared to view animations, the view properties are really changed. Note: Android 3.0 (API 11) is supported.

Audienl
Links: https://www.zhihu.com/question/19703349/answer/153065511
Source: Know
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.

Binder mechanism

Only a brief summary of the binder mechanism is presented here, and the details of the binder are not expanded here.

Http://www.linuxidc.com/Linux/2012-07/66195.htm

    • Binder is an IPC inter-process communication structure in an Android system.
      In Android, each application runs in a separate process, which ensures that one of the programs does not interfere with the normal operation of another application. In many cases, we work with the service of various systems, and it is clear that the program we write is definitely not the same process as the system service, but how do they communicate? Binder is one of the ways in which an inter-process communication (IPC) is implemented in Android.

    • Binder belongs to a driver , working at the Linux level, running in the kernel state, and its operation is done based on a memory. So the use of binders in the programs we develop is done through the call of the system.

    • Binder's entire design is the C/s structure, binder architecture by the server, Binder driver, the client three components. the client process obtains the proxy for the server-side process through binder drives and accomplishes data communication between processes by reading and writing to this proxy interface method.

Why does Android use binder for interprocess communication?

1. Security . Android is an open platform, so it's important to ensure that your application is secure. Each process is assigned the UID and PID by the Android system, where the UID of the process can be used to identify the process identity. Unlike traditional UID inclusion in a packet, this allows malicious processes to communicate directly with other processes, ensuring the security of interprocess communication.

1. Efficient . Sockets are mainly used for inter-process communication across the network and for inter-process communication on the native, but with low transmission efficiency and high overhead. Message Queuing and pipelines use storage-forwarding, where the data is copied from the sender's buffer to a buffer in the kernel, and then copied from the kernel buffer to the receiver buffer, with a process of at least two copies. Although shared memory does not need to be copied, control is complex. Compare the number of copies of data in various IPC ways. Shared memory: 0 times. Binder:1 times. socket/Pipe/Message queue: 2 times. It's important to be in a situation where the resources are tight.

Broadcast dynamic, static registration

Reference: http://blog.csdn.net/q908555281/article/details/48541939

In Android, broadcast is a widely used mechanism for transferring information between applications. Broadcastreceiver is a class of components that are filtered to receive and respond to the sent broadcast. Here is a detailed description of how to send broadcast and use Broadcastreceiver to filter the received process:

First, the information to be sent and the information used for filtering (such as action, Category) is loaded into a intent object where the message is to be sent, and then by calling Context.sendbroadcast (), Sendorderbroadcast () or Sendstickybroadcast () method, the intent object is sent out by broadcast mode.

When intent is sent, all registered broadcastreceiver will check if the Intentfilter at registration matches the intent sent, and if so, the Broadcastreceiver onreceive () method will be called. So when we define a broadcastreceiver, we need to implement the OnReceive () method.

There are two ways of registering Broadcastreceiver:

1. Static registration
Statically register the tag life in Androidmanifest.xml and set the filter in the tag with tags.

<receiver android:name=".Receiver" >              <intent-filter>                  <action android:name="android.intent.action.BOOT_COMPLETED" />              </intent-filter>   </receiver>  

2. Dynamic registration
Dynamically define and set up a Intentfilter object in the code and then call the Context.registerreceiver () method where it needs to be registered, and invoke the Context.unregisterreceiver () method if it is canceled.

UpdateBroadcast  new UpdateBroadcast();  filternew IntentFilter("com.unit.UPDATE");  filter

1. Dynamically registered broadcasts are always faster than statically registered broadcasts, regardless of the high priority setting of the static registration, regardless of how low the priority of the dynamic registration >\

2. Dynamic registration broadcasts are not resident broadcasts, which means that the broadcast follows the activity's life cycle. Note: Remove the broadcast receiver before the activity ends.

Static registration is permanent, that is, when the application is closed, if there is information broadcast, the program will be automatically run by the system call.

Some basic knowledge of interview (Android article one)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.