Basic concepts of Android (1)

Source: Internet
Author: User

What is Activity?
In other words, Activity is an interface in which various controls can be placed. The Activity interface is also represented by an xml file and placed under res-> layout. Every time a new Activity is generated, We need to register the activity in AndroidManifest. xml.


Activity Lifecycle

OnCreate (Bundle savedInstanceState): called when an activity is created. This method also provides Bundle-based access to any previously stored status!


OnStart (): called when the activity is visible to the user on the screen.


OnResume (): called when the activity starts to interact with the user (whether it is to start or restart an activity, this method is always called ).


OnPause (): This method is called when the activity is paused or the cpu and other resources are withdrawn. It is used to save the activity status and protect the site. Press the stack!


OnStop (): called when the activity is stopped and converted into an invisible stage and subsequent lifecycle events.


OnRestart (): called when the activity is restarted. The activity is still in the stack, rather than starting a new activity.


OnDestroy (): This method is called when the activity is completely removed from the system memory.

 

Function call process:

When starting the first Activity:

When onCreate () --> Activity is created for the first time, onStart () --> Activity can operate onResume ().

 


Which of the following methods must be executed when two activities are redirected?


OnCrante () // called at the beginning of the Activity Lifecycle

OnRestoreInstanceState () // used to restore the UI status

OnReStart () // called when Activity restarts

OnStart () // called when Activity is visible to users soon

OnResume () // when the Activity interacts with the user, draw the interface

OnSaveInstanceState () // called when the activity is about to be removed from the top of the stack and the UI state is retained


OnPause () // pause the current activity, submit changes to persistent data, and stop the animation and other things that occupy CPU resources. Since the next activity will not resume until this method is returned, therefore, code execution of this method is faster.

OnStop () // called when activity is no longer visible

OnDestroy () // The last method called to destroy money in Activity.


Click the button on the first Activity to jump to the second Activity through Intent:

The first Activity pauses onPause () --> creates the second ActivityonCreate () --> Activity visible onStart () --> Activity can operate onResume () --> the first Activity is completely overwritten by the second Activity onStop () (if finish () is called or the system resources are insufficient, onDestory () is destroyed ()).

 


Click system return function creation, and return to the first Activity from the second Activity:

The second Activity pauses onPause () --> the first Activity restarts OnRestart () (not destroyed. If yes, create onCreate ()) --> the first Activity is visible to onStart () --> the first Activity can operate onResume () --> The second Activity is completely overwritten with onStop () (if finish () is called (), or if the system resources are insufficient, onDestory () will be destroyed ()).

 

 


Lifecycle of the Activity during horizontal/vertical screen Switching


1. When the android: configChanges of the Activity is not set, the life cycle of the screen is re-called, the screen is executed once, and the screen is split twice.

2. When setting the Activity's android: configChanges = "orientation", the screen will be switched to call each lifecycle, and the screen will be executed only once

3. When the android: configChanges = "orientation | keyboardHidden" of the Activity is set, the live cycle is not re-called and only the onConfigurationChanged method is executed.

How to Set an Activity as a window style

 

1. Create a style similar to Dialog in your styles. xml file.

<Style name = "Theme. FloatActivity" parent = "android: style/Theme. Dialog"> </style>


2. In AndroidManifest. xml, add the following attributes to the activity that you want to display as a window: android: theme = "@ style/Theme. FloatActivity ".

You can also directly add the android: theme attribute value of the Activity that you want to display as Dialog style to android: theme = "@ android: style/Theme. dieme ".

What should I do if your background Activity is recycled by the system?


The system will record the status of the previous Activity to be recycled. The onCreate () method will be re-called when the recycled Activity is called again. The onCreate () method is different from the onCreate () method when it is started directly () contains the savedInstanceState parameter. The savedInstanceState is a Bundle object. You can basically regard it as a Map object maintained by the system for you. We can use savedInstanceState to restore to the state before recycling.

How to exit the Activity? How can I safely exit the Application that has called multiple activities?

Use the finish () method to exit the activity.

How do I transmit data between two activities?

You can add parameters to Intent objects. Add a key-value pair to the Intent object request. The object name. putExtra ("key-value pair name", "key-Value Pair value"); in another Activity, extract the data in the Intent request: Intent intent = getIntent (); // String value = intent. getStringExtra ("testIntent"); // assign the value of testIntent to value

How does one start a service when an Activity is started?

Place the statement for starting the Service in the onCreate () method

 

Can different activities of the same program be stored in different Task stacks?

It can be placed in different tasks. Different taskaffinity attributes must be set for different activities. Intent of the activity to be started must contain the FLAG_ACTIVITY_NEW_TASK tag.

How to bind an Activity to a service, and how to start its own service in the activity?

1. The Activity can be bound to interfaces benefiting from services. To support Service binding, the onBind method is implemented.

2. You can use ServiceConnection to connect services and activities. You need to implement a new ServiceConnection and rewrite the onServiceConnected and onServiceDisconnected methods. Once the connection is established, you can get reference of the Service instance.

3. Execute binding and call the bindService method to pass in an Intent (explicitly or implicitly) selected Service to be bound and a ServiceConnection instance that you have implemented

What is a Service and its lifecycle

Android Service is the code running in the background. It cannot interact with users. It can run in its own processes or in the context of other application processes. It must be called through an Activity or other Context objects, including Context. startService () and Context. bindService (). If the time-consuming operation on the Service needs to be executed, a new thread needs to be started.

Android Service only inherits the onCreate (), onStart (), and onDestroy () methods. When we start the Service for the first time, we call onCreate (), onStart () when the Service is stopped, the onDestroy () method is executed. Note that if the Service has been started, when we start the Service again, instead of executing the onCreate () method, the onStart () method is executed directly.


What are the startup methods and differences between services and how to disable services?

Two Service start methods are available: Context. startService () and Context. bindService ().

The difference is:

 

Context. startService (): the Service will go through onCreate-> onStart (if the Service is not running, android first calls onCreate () and then calls onStart (); if the Service is already running, only onStart () is called, so the onStart method of a Service may be called multiple times). When stopService is called, onDestroy is called directly. If the caller directly exits without calling stopService, the Service is always running in the background. After the Service is restarted, the Service can be closed through stopService.

Context. bindService (): the Service will go through onCreate ()-> onBind (), onBind will return to the client an IBind interface instance, IBind allows the client to call back the Service method, for example, you can obtain the Service running status or other operations. At this time, the caller (such as Activity) will be bound with the Service, and the Context will exit, and Srevice will call onUnbind-> onDestroyed to exit accordingly, the so-called binding together will survive.

Disable service using context. stopService ()

No service is required. Page B is used for playing music. It jumps from page A to page B and returns. How can I continue playing music?

A uses the startActivityForResult () method to enable class B. When Class B ends, call finish ();

Intent of Class a has a subactivity end event onActivityResult (), which continues playing music in the event.

What is IntentService? What are the advantages?

IntentService is also a Service that is a subclass of a Service. IntentService and Service are different. It uses logoff and Thread to solve the blocking problem of processing logic in standard Service.

Advantage: The acitiworkflow process generates a corresponding Service when processing Intent.

The Android process processor will try not to kill you

Very easy to use

IntentService application in calendar

When to use Service?

For example, when the user starts other activities during multimedia playback, the program will continue playing in the background, for example, detecting file changes on the SD card, or recording changes to your location in the background, in short, services are always hidden behind the scenes.

Describe Intent and Intent Filter


Intent is translated as "Intent" in Android. In terms of idioms, it is the purpose. They are three basic components of an application-activity, service, and broadcast receiver. When the Intent name is called, The ComponentName, that is, the full name of the class, is displayed. This method is generally used for internal calls of applications, because you may not necessarily know the full name of the class written by others. Let's see how to use the implicit Intent? First, configure the Intent Filter of our Activity.

<Intent-filter> <actionandroid: name = "com. example. project. SHOW_CURRENT"/> </intent-filter>

In this way, the Intent action is specified during the call, and the system automatically compares the intent-filter that conforms to our Activity. After finding it, the Activity will be started.

An intent filter is an instance of the IntentFilter class, but it generally does not appear in the code, but appears in the android Manifest file, in the form of <intent-filter>. (one exception is that the intent filter of broadcast receiver uses Context. registerReceiver () is dynamically set, and its intent filter is also created in the Code .)

A filter has fields such as action, data, and category. an implicit intent must pass three tests in order to be accepted by an intent filter. to be accepted by a component, an intent must use one of all its intent filters.

What types of data can be transferred when Intent transmits data?

There are two common methods to transmit data between Intent:

1. extra

2. data.

Extra can be used to put data with Intent. putExtra. The newly started Activity can use Intent. getExtras to obtain the Bundle, and then use functions such as Bundles. getLong, getInt, getBoolean, and getString to obtain the entered value.

Data is the transmission url. Url can be a familiar http, ftp, or other network address, or content can be used to direct to resources provided by ContentProvider. Intent. setData can be put into data, and Intent. getData can be taken out.

What is the relationship between Activity, Intent, and Service?


An Activity is usually a single screen, and every Activity is implemented as a separate class. These classes are inherited from the base class of the Activity, the Activity class displays user interfaces composed of View Controls and responds to view control events.

Intent calls are used to switch between architecture screens. Intent describes what the application wants to do. In the Intent data structure, the two most important parts are the data corresponding to the action and action, and one action corresponds to one action data.

Android Service is the code running in the background. It cannot interact with users. It can run in its own processes or in the context of other application processes. It needs to be called through an Activity or other Context object.

The Activity jumps to the Activity, and the Activity starts the Service. When the Service opens the Activity, Intent indicates the intention of the jump and transmits parameters. Intent is the carrier of signal transmission between these components.

Describe Broadcast Receiver

 

The Broadcast Receiver is used to receive and process broadcast notifications (Broadcast announcements ). Most broadcasts are initiated by the system, such as region change, insufficient power, and incoming calls. The program can also play a broadcast. The program can have any number of broadcast receivers to respond to the notifications it deems important. Broadcast Explorer can notify users in multiple ways: Start activity, use NotificationManager, enable background light, vibrate device, and play

Sound, etc. The most typical is to display an icon in the status bar, so that users can click it to open the notification content. Generally, an application or system will broadcast an Intent temporarily in some events (insufficient battery or short message calls, we can register a Broadcast Receiver to listen to the Intent and obtain the data in the Intent.

How to register and use broadcast receiver in manifest and code

 

1) Register in AndroidManifest. xml

<Cycler android: name = "Receiver1">

<Intent-filter>

<! -- Corresponds to the action in Intent -->

<Actionandroid: name = "com. forrest. action. mybroadcast"/>

</Intent-filter>

</Cycler>

2) register in the code

1. IntentFilterfilter = newIntentFilter ("com. forrest. action. mybroadcast"); // corresponds to the Intent action in the broadcast.

2. MyBroadcastReceiverbr = newMyBroadcastReceiver ();

3. registerReceiver (newMyBroadcastReceiver (), filter );

This section describes how ContentProvider achieves data sharing.

 

ContentProvider provides a Uri for data sharing.

Describes how to store Android data.

 

Android provides five Data Storage Methods: Using SharedPreferences to store data, file to store data, SQLite database to store data, ContentProvider to store data, and network to store data;

Why ContentProvider? What is the difference between SQL and SQL?

 

You can use ContentProvider to share data with other applications so that applications other than this application can also access the data of this application. Its underlying layer is implemented using the SQLite database, so all its operations on data are implemented using SQL, but Uri is provided at the upper layer.

Introduce the five commonly used la s in Android


The most common layout methods are LinearLayout, RelativeLayout, FrameLayout, and TableLayout AbsoluteLayout. Among them, LinearLayout and RelativeLayout are the most common methods. They can be laid out in xml configuration files or code.

 

FrameLayout is the simplest layout method. The placed controls can only be listed in the upper left corner. The controls overlap and do not carry out complex la S. This layout can be seen as a heap of the wall. There is a wall foot in the upper left corner of the rectangular square. We put the first thing, and we want to put another one, which is placed on the top of the original place, in this way, it will cover the original things. This layout is relatively simple, and you can only put something simple.


LinearLayou can use the orientation attribute to set whether the direction of the linear arrangement is vertical or horizontal. Each row or column has only one element, and Complex layout can be performed.

AbsoluteLayout allows the child element to specify an accurate x/y coordinate value and display it on the screen. AbsoluteLayout has no page border and allows elements to overlap with each other (although not recommended ). It is an absolute coordinate, so it is not recommended in practice.

RelativeLayout allows child elements to specify their positions relative to other elements or parent elements (by ID ). Therefore, you can arrange two elements in the right-aligned, up/down, or in the center of the screen. Elements are arranged in order. Therefore, if the first element is in the center of the screen, other elements relative to the element are arranged in the relative position in the center of the screen. This is relative to AbsoluteLayout and uses relative coordinates, so it is usually used in practice.

TableLayout distributes the positions of child elements to rows or columns. A TableLayout consists of many TableRow. Each TableRow defines a row. The TableLayout container does not display the border lines of row, column, or cell. Each row has 0 or more cells, which is similar to the table in html. It is also frequently used in practice.

Sometimes we will also use the GridView, just like the icons on our mobile phone screen should be formatted using the GridView. Padding is the text relative to the border, while Margin is the border relative to the parent form.

What is the difference between Padding and Margin in the UI?


Padding is the text relative to the border, while Margin is the border relative to the parent form.

What is the full name of AIDL? How to work? What types of data can be processed?

 

AIDL is an interface definition language used to constrain communication rules between two processes for the compiler to generate code and implement inter-process communication on Android devices.

The communication information between processes is first converted to AIDL protocol messages, and then sent to the other party. The other party receives AIDL protocol messages and then forwards the messages to the corresponding objects.

The types supported by AIDL include basic Java types and String, List, Map, and CharSequence. If you use custom types, you must implement the Parcelable interface.

Please explain the difference between the permission for running Android programs and the permission for the file system.

Dalvik at runtime (android authorization)

File System linux kernel authorization

How to load music information and improve its efficiency.

 

The Android system provides interfaces such as MediaScanner, MediaProvider, and MediaStore, as well as a set of database tables, which are provided to users through Content providers. When a mobile phone is turned on or has SD card plugging or removal, the system will automatically scan the media files on the SD card and mobile phone memory, such as audio, video, and images, put the corresponding information in the defined database table.

To improve efficiency, You can query the required data from the interface.

How can ListView improve its efficiency?

Use paging loading instead of loading all data at once

 

Start a program, you can click the icon on the main interface to enter, you can also jump from a program in the past, what is the difference between the two?

Starting an application from the main interface directly calls mainActivity through shortcuts. calling other applications requires implicit Action or setClass () in Intent (), specify the package path.

What is the difference between Android and Java?

The android program is written in Java, but the android-developed API used by the program is the andriod library.

This article describes how to understand Android NDK.

Android NDK is a set of tools that allow Android Application developers to embed local machine code compiled from C, C ++ source code files into their respective application software packages.

In Android, when does GC cause memory leakage?

Case: 1. the database cursor is not closed. 2. when constructing an adapter, the optimization problem of listview derived from the cache contentview is not used-reduce the object for creating the view and make full use of contentview. You can use a static class to optimize the getview processing process/3. when the Bitmap object is not in use, use recycle () to release the memory 4. the object lifecycle in the activity is greater than the activity debugging method: DDMS ==> HEAPSZIE ==> dataobject ==> [Total Size]

How to refresh the View in the Android UI.


Generally, you only want to re-paint the UI when the View changes. You only need to explicitly call the invalidate () method in the View object in the Activity. The system automatically calls the onDraw () method of View.


What are the features and differences of animations in android?

 

Two types: Tween animation and Frame animation. Tween animation, which allows view components to move, zoom in, zoom out, and change transparency. Another Frame Animation, the traditional animation method, it is achieved through sequential playback of arranged images, similar to movies.

The animation effect is defined in the xml file under the anim directory. in the program, use AnimationUtils. loadAnimation (Context context, int ResourcesId) is loaded into an Animation object. When you need to display the Animation effect, execute the startAnimation method of the View to be animated and pass in the Animation. You can also apply the animation effect when switching Activity. After the startActivity method is used, the overridePendingTransition method is executed. The two parameters are the animation effect before switching and the animation effect after switching.

The principle of the handler mechanism.


Andriod provides Handler and Looper to satisfy inter-thread communication. Handler first-in-first-out principle. Looper class is used to manage Message Exchange between objects in a specific thread)


1) loue: A thread can generate a loue object to manage the Message Queue (Message Queue) in this thread ).

 

2) Handler: You can construct a Handler object to communicate with logoff, so as to push new messages to the Message Queue, or receive messages sent by logoff from the Message Queue.

3) Message Queue: used to store messages placed by threads.


4) thread: the UI thread is usually the main thread, and Android will create a Message Queue for it when starting the program.


How to communicate between threads and processes in android

1. When an Android program starts running, a Process is started separately.
By default, all the activities or services in this program run in this Process.
By default, an Android program also has only one Process, but a Process can have many threads.
2. When an Android program starts running, a Main Thread is created. This Thread is mainly responsible for display, update, and control interaction of the UI interface, so it is also called the UI Thread.
At the beginning of an Android program, a Process presents a single-threaded model, that is, the Main Thread. All tasks are run in one Thread. Therefore, the shorter the time consumed for each function called by Main Thread, the better. For time-consuming work, we should try to hand it over to the sub-thread to avoid blocking the main thread (the main thread is blocked, and the program will be suspended ).

3. Android single-threaded model: Android UI operations are not thread-safe and must be executed in the UI thread. If you modify the UI directly in the Child thread, an exception occurs.


Let's talk about the principles of the mvc Pattern and Its Application in android

 

MVC (Model_view_contraller) "model _ view_controller ". The MVC application is always composed of these three parts. Event causes the Controller to change the Model or View, or change both. As long as the Controller changes the data or attributes of Models, all dependent views are automatically updated. Similarly, as long as Contro

The listening operations on various interfaces in Android are MVC applications.


How to publish the SQLite database (dictionary. db file) with the apk file?
You can copy the dictionary. db file to the res raw directory of the Eclipse Android project. All files in the res raw directory are not compressed, so that files in the directory can be extracted directly. You can copy the dictionary. db file to the res raw directory.

 

Information about common Android controls

Single partition (RadioButton and RadioGroup ):

RadioGroup is used to group A single region. Only one region in the same group is selected.

Event: setOnCheckedChangeListener () to process the selected event of a single token. Input the RadioGroup. OnCheckedChangeListener instance as a parameter.

Multi-choice box (CheckBox ):

Each multiple-choice box is independent. You can iterate all the multiple-choice boxes and obtain their values based on whether their statuses are selected.

Event: setOnCheckedChangeListener () is used to process selected events in the Multi-choice box. Pass in the CheckBox. OnCheckedChangeListener () instance as a parameter.

Drop-down list box (Spinner ):

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

Event: setOnItemSelectedListener (), processing the event selected in the drop-down list box, and passing in the instance of Spinner. OnItemSelectedListener () as a parameter.

Drag bar ):

SeekBar. getProgress () Get the current value of the drag bar

Event: setOnSeekBarChangeListener () is used to handle the event of changing the drag value. The SeekBar. OnSeekBarChangeListener instance is passed in as a parameter.

Menu ):

Override the onCreatOptionMenu (Menu menu) method of the Activity. This method is used to create the option Menu. When the user presses the "Menu" button on the mobile phone, the created Menu is displayed. In onCreatOptionMenu (Menu menu) you can call Menu. add () method to add a menu.

Override the onMenuItemSelected () method of the Activity to process the selected menu events.

Progress dialog box (ProgressDialog ):

Create and display a progress dialog box: ProgressDialog. show (ProgressDialogActivity. this, "Please wait", "data loading...", true );

Set the style of the dialog box: setProgressStyle ()

ProgressDialog. STYLE_SPINNER rotation progress bar style (default style)

ProgressDialog. STYLE_HORIZONTAL horizontal progress bar style

The following describes how to use event listening for various commonly used controls.
① EditText (edit box) event listening --- OnKeyListener
② RadioGroup and RadioButton (single-choice button) event listening --- OnCheckedChangeListener
③ Event listening for CheckBox (multiple-choice button) --- OnCheckedChangeListener
④ Event listening for the Spinner (drop-down list) --- OnItemSelectedListener
⑤ Menu event processing --- onMenuItemSelected
⑥ DialogInterface. OnClickListener ()

 


 

Related Article

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.