Android knowledge set 2

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

  Basic knowledge on to an article related Android, preparing for the interview may have a look what knowledge is missing. The information is online order, corrected some errors, some analytical add personal understanding! Thank you for sharing knowledge related to the developer. These knowledge common development are often used, past~

16.Android common control information

Radio buttons (RadioButton and RadioGroup)

RadioGroup is used to group of radio buttons, the same group of radio buttons only one radio button is selected.

Event: setOnCheckedChangeListener (), processing check box selected events. The RadioGroup.OnCheckedChangeListener instance is passed as a parameter.


Each checkbox is independent, can be obtained by iterating all checkbox, then according to its state is selected in the acquisition of its value.

Event: setOnCheckedChangeListener (), processing checkbox selected events. The CheckBox.OnCheckedChangeListener instance is passed as a parameter ().

The drop-down list box(Spinner)

Spinner.getItemAtPosition(Spinner.getSelectedItemPosition());Gets the value of the drop-down list box.

Event: setOnItemSelectedListener (), frame selected events to Spinner.OnItemSelectedListener drop-down list () instance is passed as a parameter.

Drag strip(SeekBar)

SeekBar.getProgress()Gets the current value of the drag

Event: setOnSeekBarChangeListener (), handling of drag bar values change, the SeekBar.OnSeekBarChangeListener instance is passed as a parameter.


Override the Activity onCreatOptionMenu (Menu menu) method, this method is used to create a menu of options, when the user presses the mobile phone "Menu" button will display to create good menu, in the onCreatOptionMenu (Menu Menu) method can call Menu.add () method to realize the menu to add.

Override the Activity onMenuItemSelected () method, the method for processing the menu selected events.

A progress dialog(ProgressDialog)

Create and display a progress dialog: (ProgressDialogActivity.this, "please wait", "data is loaded. In...", true),

The settings dialog box style: setProgressStyle()

ProgressDialog.STYLE_SPINNER rotary progress bar style (the default style)

ProgressDialog.STYLE_HORIZONTAL horizontal progress bar style

The following is the use of a variety of commonly used control event monitoring
The EditText (edit box) event ---OnKeyListener
②RadioGroup, RadioButton (radio button) event ---OnCheckedChangeListener
③ CheckBox (checkbox) event ---OnCheckedChangeListener
The Spinner (event ---OnItemSelectedListener drop-down list)
The Menu event handling ---onMenuItemSelected (menu)
The Dialog (dialog) event ---DialogInterface.OnClickListener()

17 please introduce five kinds of commonly used layout in Android

  Android layout is the application interface development is important one annulus, in Android, there are five kinds of layout, respectively is: FrameLayout (frame layout), LinearLayout (linear layout), AbsoluteLayout (absolute layout), RelativeLayout (relative layout), TableLayout (layout).


      This layout can be regarded as a bunch of things, there is a rectangle with a square in the upper left corner of the wall, we put the first things, to put a, just above them in their original position, and so on, can cover the original thing. This layout is simple, also can put a little something relatively simple.    


      Linear layout, this thing, from the frame can be understood as a div, he is the first one down from the list on the screen. Each LinearLayout can be divided into vertical layout (android:orientation= "vertical") and horizontal layout (android:orientation= "horizontal"). When the vertical layout, each row has only one element, a plurality of elements are vertically down; horizontal layout, only one line, each element in turn right arrangement.    

There is an important attribute android:layout_weight= "1" LinearLayout, set the weight, according to the set weight values, the distribution of residual space for tensile space, the parent control all of the positions occupied.


      Absolute layout is like div, the absolute attribute is specified, X, Y coordinates to specify the location of the android:layout_x= "elements of the 20px" android:layout_y= "12px" this layout is relatively simple, but in the vertical random switching, often a problem, and a number of elements when compared trouble,.    


    Relative layout can be understood as a certain element as reference, layout to locate. The main attribute:    

    With respect to a certain element   

    android:layout_below="@id/aaa" The elements in the ID below AAA   

    android:layout_toLeftOf="@id/bbb" The elements in the ID BBB left    

     Relative to the parent element.   

     android:layout_alignParentLeft="true" And the parent element align left   

     android:layout_alignParentRight="true" And the parent element right aligned   

     You can also specify margins, specific see API


     Table layout similar Html inside the Table. Each TableLayout has a table row TableRow, TableRow can be defined for each element, set the android:gravity his alignment="" .    

     Each layout has their own ways, in addition, the five layout elements can be nested within each other, make beautiful interface.

18 how to enable Service, how to disable Service

  The Android service and windows service is something similar, service generally do not have a user interface, it runs in the system is not easy for users to find, it can be used as surveillance, program development. Service development is relatively simple, as follows:

//The first step: to inherit from the Service class
public class SMSService extends Service


//The second step: in the AndroidManifest.xml files <application> node on the service configuration:
<service android:name=".SMSService" />

  Service cannot run, need to call Context.startService () or Context.bindService () method to start the service. These two methods can start Service, but they use different. Use the startService () method enabled services, no correlation between the caller and the service, even if the caller quit, service is still running. Use the bindService () method enabled services, the caller and the service is bound together, the caller as soon as the exit, service is terminated, a “ not at the same time, must also die ” characteristics.

  If you intend to use Context.startService () method to start the service, the service has not been created, the system will first invoke the service (onCreate) method, and then call onStart () method. If you call startService () method of service has been created, repeatedly call startService () method will not lead to repeatedly create service, but can lead to multiple calls to onStart () method. Using startService () method to start the service, can only call Context.stopService () method to end service, the end of the service will call onDestroy () method.

  If you intend to use Context.bindService () method to start the service, the service has not been created, the system will first invoke the service (onCreate) method, and then call onBind () method. This time the caller and the service is bound together, the caller to exit, system will invoke the service onUnbind () method, and then call onDestroy () method. If you call bindService () service is already bound method, multiple call bindService () method does not cause many to create the service and binding (that is onCreate () and onBind () method will not be called multiple times). If the caller wants to lift binding and binding is service, you can call unbindService () method, calling this method will cause the system to invoke the service onUnbind (-->); onDestroy () method.

The following service common lifecycle callback methods:

onCreate() Calling this method is created in the service, the method will only be invoked once, regardless of how many times (called startService) or bindService () method, the service will only be created once.

onDestroy()Calling this method is terminated at the service.

And the Context.startService () method to start the service life cycle method related

onStart() Only by adopting the Context.startService () method to start the service only when the callback method. This method is called in the service starts running. Multiple calls to startService () method, although not many times to create the service, but the onStart () method can be called multiple times.

And the Context.bindService () method to start the service life cycle method related

onBind()Only by adopting the Context.bindService () method to start the service only when the callback method. This method is called in the caller and the service binding, when the caller and the service is bound, repeatedly call Context.bindService () method does not cause the method onBind () is called multiple times.

onUnbind()Only by adopting the Context.bindService () method to start the service only when the callback method. The method of unbound in the caller and the service is invoked

//The bindService (Context.) code method to start the service.: 
public class HelloActivity extends Activity 
{ ServiceConnection conn
= new ServiceConnection()
public void onServiceConnected(ComponentName name, IBinder service)
       { }
public void onServiceDisconnected(ComponentName name)
       { } };
public void onCreate(Bundle savedInstanceState)
   { Button button
=(Button) this.findViewById(; button.setOnClickListener(new View.OnClickListener()
public void onClick(View v)
         { Intent intent
= new Intent(HelloActivity.this, SMSService.class); bindService(intent, conn, Context.BIND_AUTO_CREATE); //unbindService(conn);//Unbound }}); } }

The optimization scheme of 19.ListView

1, If the custom adapter. Then the getView method should be taken into account in the contentView method parameter passed is null, if NULL creates and returns contentView, if not null then used directly. In this method, as little as possible to create view.
2, Setting tag to contentView(setTag()),Pass a viewHolder object, is used to cache data to display image data, can achieve asynchronous loading effect
3, If the listview item to display a lot, it must consider the paging load. For example, a total of 100 or more times, we can consider the loading of 20, when the user to pull at the bottom of the list, and then to load the next 20.

20 broadcast receiver life cycle

//The broadcast receiver only a callback method: 
void onReceive(Context curContext, Intent broadcastMsg)
  When the broadcast message arrives at a receiver, Android calls its onReceive () method and the message containing the Intent object passed to it. A broadcast receiver is active only in the implementation of this method. When the onReceive () returns, it is inactivated state.
The broadcast receiver has an active state of the process to be protected and not be killed. But only with inactivated state assembly process will need it occupied memory in other processes to be killed.
  This raises a question: if the response to a broadcast information needed for a long time, we will put it into a derivative of the thread to complete, not in the main thread to finish it, so as to ensure the smooth process of user interaction. If the onReceive () derived a thread and returns, the new thread is covered the whole process would be sentenced to the inactive state (unless other application components within the process still is active), then it is likely to be killed. The solution to this problem is to make onReceive () to start a new service, and complete the task, so the system will know the process is still in the process of work.

21 design patterns and IoC (Inversion of Control inversion of control)

  Source Android framework charm lies in IoC, in the process of designing Android you will feel the great convenience brought by IoC, take the Activity, the following function is invoked automatically invoke framework:

protected void onCreate(Bundle savedInstanceState)

  Not a programmer to call, but the user written code is called by the framework, which is reversed! Of course, the connotation of IoC itself is far more than these, but from this example can also peep out great benefits brought by IoC. Such examples in the Android can be seen everywhere, such as database management, for example, Android SAX Handler calling. Sometimes, you even need to write your own simple IoC implementation, multi thread shown above is now a description.

The length of the 22.Android unit.

  Now here to introduce DP and SP. DP is dip. The basic SP and similar. If you set the length, height and other properties that you can use the DP or SP. But if you set the font, need to use sp. DP is independent of density, density independent SP except outside, also has nothing to do with scale. If the screen density is 160, then DP and SP and PX are the same. 1dp=1sp=1px, But if you use the PX as a unit, if the screen size unchanged (hypothesis 3.2 inch), and the screen density became 320. So that the width of the TextView is set to 160px, the density of 320 3.2 inch screen look than in the density of 160 3.2 inch screen read short half. If set to 160dp or 160sp. The system will automatically sets the width property value into 320px. It is 160 * 320 / 160. 320 / 160 can be called density scaling factor.

That is to say, if the use of DP and SP, the system will automatically convert according to the change of screen density.

Let's look at the other units of meaning

px: The actual pixel screen. For example, the 320*480 screen is 320 pixels in horizontal, vertical 480 pixels in the.

in: Said., Is the physical size of the screen. Every inch is equal to 2.54 cm. For example, describe the mobile phone screen size, often say, 3.2 (in English) ", 3.5 (English)", 4 (English) "refers to this unit. These dimensions are the diagonal length of the screen. If the mobile phone screen is 3.2 inches, said mobile phone screen (visual area) the diagonal length is 3.2*2.54 = 8.128 cm. Readers can go to measure their own mobile phone screen, and the actual size is consistent.

Boot mode 23.4 activity

Standard: standard mode, A call startActivity () method will produce a new instance.

singleTop: If you already have a top of a case is located in the Activity stack, it does not create new instance, just call the Activity in the newInstance () method. If not at the top of the stack, creates a new instance.

singleTask: This example will produce in a new task, after each call will use this, not to create new instances.

singleInstance: This is basically the same as with singleTask, there is only one difference: in this mode the Activity instance of the task, only the activity instance, can not have other examples.

24 what is ANR and how to avoid it?

ANR: Application Not Responding.

  In Android, in response to the two system service manager and window manager is responsible for monitoring applications. When any of the following circumstances, Android will show the ANR dialog box.:

  Android applications run entirely on a separate thread (such as main). This means that, for any operation in the main thread, time-consuming operation will cause ANR. Because of this, your application has no chance to response to input events and broadcast intent(Intent broadcast).

Avoid methods:

  Activity should be the key which the life-cycle approach (such as onCreate () and onResume ()) in as little as possible to do the create operation, potentially time-consuming operation. For example, a network or database operations, or computationally expensive calculations such as changing bitmap size, should be in the child thread (or asynchronous mode) to complete the. The main thread should provide a Handler as the thread, in order to complete can be submitted to the main thread.

The use of 25.Android Intent

  In a Android application, is mainly composed of some components, (Activity, Service, ContentProvider, etc.) in the communication between these components, the Intent assist. Just as some people on the Internet analysis said, Intent is responsible for an application in action, action relates to data, additional data are described, the Android according to the description of Intent, is responsible for finding the corresponding components, the Intent is passed to the calling component, and complete the assembly call. Intent plays a role in the realization of the caller and callee decoupling between the here.

  Intent transfer process, to find the target consumers (another Activity, IntentReceiver or Service), response is the Intent, there are two ways to match:
1, Display matching(Explicit):

public TestB extents Activity
 public class Test extends Activity
     public void switchActivity()
            Intent i = new Intent(Test.this, TestB.class);

Concise code, the implementation of switchActivity () function, will immediately jump into a TestB Activity.

2, Implicit matching(Implicit):
Implicit matching, first of all to several value matching Intent: Action, Category, Data/Type, Component. If you fill in the Componet is in Test.class) which formed the display matching. So this part is only about several matching. The matching rule matching rules for maximum,

  1, If you fill in the Action, If the IntentFilter segment of a Activity has a program in Manifest.xml are defined in the same Action then the Intent with the Action match, if there is no definition of the Type, the Filter segment in Category, then the Activity will match. But if the mobile phone has two or more matching procedure, so it will pop up a dialog box to indicate that can.
The value of Action have many predefined in the Android, if you want to go directly to your own definition of the Intent receiver, you can add a custom in the recipient's IntentFilter value in the Action (at the same time to set the Category value of "android.intent.category.DEFAULT"), set the Intent value for the Action in your Intent, you can directly jump into your own Intent receivers. Because the Action in the system is the only.
  2,data/type, You can use Uri to do data, such as Uri URI = Uri.parse( );Intent i = new Intent(Intent.ACTION_VIEW,uri);Mobile phone Intent distribution process, according to the Scheme determine the data type type mobile phone Brower can match it, at the Brower Manifest.xml IntenFilter ACTION_VIEW Action first, but also can deal with the http: type.

  3, As for the classification of Category, Don't set it in Intent receiver, if you write the Intent, include the android.category.DEFAULT in the Manifest.xml Activity IntentFilter, so that all do not set Category (Intent.addCategory (String; c)) Intent will match with the Category.

  4,Extras (additional information), Is the set of all other additional information. The use of extras can provide extended information, for components such as, if you want to perform “ &rdquo email; this action, can be an email, text stored in the extras, send e-mail component.

Above is the relevant knowledge about Android, if found wrong please point out where.

Edited by mythou

OriginalityBowen, reprint please indicate the source

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Lorraine at November 21, 2013 - 2:42 AM