A summary of the most detailed and basic Android interview knowledge points in history (i)

Source: Internet
Author: User

1. What is activity?

The answer to this question, first Activity is one of the four components, is a View object container, can be used to show an interface, through the Setcontentview (),//method to set the layout to display

Activity is a subclass of context objects that implements both the Window.callback and Keyevent.callback interfaces, so activity can respond to interactions with the form and the user, as well as keyboard-related events. (Contextual context object, actually is a variable, maintains the Android application some common environment reference, for example, through the context, we can get the resource Management Service, the system's asset directory, or through Getcachdir () obtains the current application to run the directory, Once the context is obtained, it is equivalent to getting a reference to a known relevant environment. You can rewrite onkeydown ontouchevent to handle form events when you get the activity.

2. Describe the life cycle of your activity?

The life cycle, which describes a class, is a method that executes from the creation (new) to the Death (garbage collection) process, in which different methods are called for different life stages.

Activity can be destroyed from the creation of multiple states, from one state to another to fire the appropriate method. These callback methods include, OnCreate OnDestroy onstart onstop onresume OnPause, these methods are 22 corresponding OnCreate created with OnDestroy destroyed. OnStart visible with OnStop invisible onresume editable (gets to focus) and OnPause loses focus. There is also a situation when the activity is stop off, but is not destroy, the Onrestart method is called when the activity is started again (without calling OnCreate). If it is destroy, then OnCreate will be called.

In conjunction with the project, in order to ensure that each entry to the activity to see the interface is up-to-date, we write this operation into the OnStart method. or check the network (check for networking every time you enter the interface). Video playback, such as watching the video, there is a phone call, then we need to pause the video player, this operation in the OnPause or OnStop method is better, and then in the onresume inside to resume playback.

Commonly used in C is the above methods and some methods can be understood as extensions such as Onpostresume onpostcreate This is the system itself calls, in the execution of Onresume OnCreate will be executed.

3. What methods the activity performs when jumping.

Generally from a activity jump to B activity first a activity will lose focus (OnPause) becomes invisible (onstop) B activity in Creation (OnCreate) visible (onstart) Get Focus (onre Usme), but some special cases, such as setting the activity background of B to be transparent, or dialog style, then a activity is visible after losing focus, so the OnStop method is not executed.

4. The life cycle of the activity when the screen is switched.

This life cycle is related to the configuration in the manifest file.

1. When the activity android:configchanges is not set, the toggle screen will recall the life cycle method first OnPause onstop OnDestroy then oncreate onstart onresume .

If we set Configchanges to android:configchanges= "Orientation|keyboardhidden", the default will not be destroyed in the creation, but I found on my phone, turn on the automatic rotary screen, as well as  is to be destroyed in the creation, turn off the rotary screen on no problem. In general development we will set the activity to orentation.


5. How do I exit the activity and safely exit the application that invokes multiple activity?

Exiting activity directly calls the Finish method (for example, the user clicks the Back button to exit an activity), and exiting the activity executes the OnDestroy method.

1, exit unexpectedly, throw an exception when exiting, such as a null pointer to make the program force close, such as

Import Java.lang.Thread.UncaughtExceptionHandler;
Import Android.os.Bundle;
Import android.app.Activity;
Import Android.view.Menu;
Import Android.view.View;
Import Android.view.View.OnClickListener;
public class Mainactivity extends Activity implements Onclicklistener {
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Thread.setdefaultuncaughtexceptionhandler (New Extappexceptionhandler ());//sets the default uncaught exception Handler. This handler was invoked in case any Thread dies due to an unhandled exception
Findviewbyid (R.ID.BTN). Setonclicklistener (this);
}
@Override
public boolean Oncreateoptionsmenu (Menu menu) {
Inflate the menu; This adds items to the action bar if it is present.
Getmenuinflater (). Inflate (R.menu.main, menu);
return true;
}

String s;
public void Extapp () {
// try {
S.equals ("AAA");//Here S is not initialized, will definitely throw an exception, if we want to exit the program will intercept the pop-up crash window (note Do not capture yourself, otherwise it will be intercepted)
// } catch (Exception e) {
// TODO auto-generated Catch block
// E.printstacktrace ();
// }

}
Class Extappexceptionhandler implements uncaughtexceptionhandler{


@Override
public void uncaughtexception (thread thread, Throwable ex) {
Android.os.Process.killProcess (Android.os.Process.myPid ());//This kills the current process. Quit App
}

}


@Override
public void OnClick (View v) {

Extapp ();
}


}

2, you can define a collection, add the current activity to the collection each time you enter the activity, and remove the current activity that you added in each activity's OnDestroy method. (above can be in baseactivity), and then when we exit the app to facilitate this collection, each of the finish ().

3. We can also broadcast, register a broadcast in each activity, send a broadcast when we exit and finish off each activity.


The above three kinds are more commonly used to close the operation of the app.


When asked to understand the activity of the question can answer the above points.


6. If the service is in main thread, the service can take a time-consuming action.

By default, the service and activity are running in the main thread (UI thread) of the process in which the current app is located, so there is no time-consuming operation to display the specified service.

If the service takes time-consuming action, you can either open a sub-thread in the service or initialize a servicehandler using Intentservice (Intentservice OnCreate method). In Onhandleintent this interface we can perform time-consuming operations) so that the service is not executed in the main thread, you need to register the service Android in the manifest file:p rocess= "other process"


7. Transfer data between two activity modes.

Generally through intent. Intent can pass basic types as well as objects (implementing serialization or parcel packets) or bundle bundles implement bundles implements parcelable internally maintain a hashmap. The bundle can be interpreted as a map put key value to store the data.

8. How to start a service when an activity is started.

You can call the StartService method in the OnCreate method of the activity.

9 whether the activity in the same program can be placed in a different task stack.

You can set intent.setflags (intent.flag_activity_new_task) for the activity by intent when a new activity is opened. Note that when we open an activity in service or broadcastreceiver, it is important to note that flag is set because there is no task stack by default in both components. (combined with Launchmode)

How the service is started.

There are two ways to open a service. One is StartService one is bindservice.

Once the StartService is opened, it has no relationship with the caller. This service will run in the background for a long time.

Bindservice is to bind the caller to the service, and if the activity that opened the service is destroyed, then the service will be hung up accordingly.

Bindservice has a feature that allows us to invoke the methods in the service indirectly. Bindservice (Intent service, serviceconnection conn, int Flags) Serviceconnection Two methods onserviceconnected (componentname name, IBinder service) onservicedisconnected ( ComponentName name)

11 describes the life cycle of the service, what is the difference between service startup methods, and how to stop the service.

Service life cycle is less than activity, common only oncreate onstartcommand onbind onunbind OnDestroy these.

typically two startup modes One is StartService, one is bindservice.

Once the StartService is opened, it has no relationship with the caller. This service will run in the background for a long time. ’

Bindservice is to bind the caller to the service, and if the activity that opened the service is destroyed, then the service will be hung up accordingly.

Bindservice has a feature that allows us to indirectly invoke the methods in the service Bindservice (Intent service, serviceconnection conn, int flags) Servicecon Nection two methods onserviceconnected (componentname name, IBinder service) onservicedisconnected (componentname name)

Two startup modes have different effects on the service life cycle

by StartService Way

Service will go through OnCreate Onstartcommand and then be in a running state, stop OnDestroy Note If you write the service as an internal class (broadcast with internal affinity) Be sure to add the service class to the front of the static modifier no Will be reported no empty constructor such a mistake, can not initialize the service, and in the manifest file declaration internal class when the format is similar to <service android:name= ". Mainactivity$myservice "/> External class mainactivity+ inner class

If you start the service by Bindservice Way.

Then the corresponding execution OnCreate onbind when the activity exits will be executed Onunbind OnDestroy,

PS: Remember we in the activity of the OnDestroy method to perform the next stopservice or Unbindservice, otherwise will be error activity has leaked Serviceconnection, you should override the OnDestroy method, unbind,

One of the principles of service is whether the first start or bind OnCreate method executes only once, in other words, no matter how many times you execute StartService or Bindservice service is created only once,

Multiple calls to the StartService OnStart method are called more than once, and multiple calls to the Bindservice Onbind method are performed only once, and only once for multiple destroy. Multiple calls to Unbindservice will report an exception.


12 What is intentservice and what are the advantages?

The normal service runs in the UI thread by default, while the Intentservice internally maintains a handler we use Intentservice as long as the Onhandleintent interface can do time-consuming operations on this interface, note that we Use Intentservice when you want to add an empty parameter of the construction method, or will be initialized Intentservice when the error instantiationexception.

Intentservice is a service class with asynchronous processing provided by Android.


13 When do I use the service?

For the Google Developer documentationProcessesforeground process ) visible processes ( visible process"   Service processes (service process" background process ( background process" empty processes ( empty process"

Low-priority processes are easily recycled when the system is out of memory, and the higher the priority, the more it is recycled.

Introduction to the service process: a process, which is running a service, that have been started with thestartService()method and does not fall into either of the higher categories. Although service processes is not directly tied to anything the user sees, they is generally doing things that the user Cares about (such as playing music in the background or downloading data on the network), so the system keeps them running Unless there ' s not enough memory to retain them along with all foreground and visible processes.


Empty process: is to press the back key to exit the future process, when the system memory is not sufficient to first reclaim the empty process.

Background process, that is, after pressing the home key to run the app in the background, the activity executes the OnStop method, when the system memory is low, may attempt to reclaim the background process. The Onsavedinstance method is executed when the activity of the background process is destroyed.

Service process: When a process R has a service runtime such as the application to open the service to play music, download data, etc., the system will try to maintain a service process, know that the memory is insufficient, will try to recycle the service process. This is why some time-consuming operations are performed in the service rather than opening a sub-thread in the activity because the activity priority is low and easy to be recycled, and the current process becomes a background process or an empty process after the current activity is recycled, and is easily recycled. If the process is recycled, then the thread is also hung up, so in order to keep our application running in the background, we typically use the service component to start the thread execution time-consuming operation. This will ensure that our process is not easily recycled.

Foreground process: The screen can be seen directly, such as launcher is a foreground process, can respond to our interactive events

Visible process: Just can see, for example, we will be a mainactivity set theme transparent, then this application is the foreground process, the back of the launcher is visible process.

Setting Setforground (True) for a service can make services similar to a foreground process, ensuring that services are not recycled as much as possible. Service features can be run in the background, so the general time-consuming operation is placed here, such as the broadcast receiver receives a broadcast to do time-consuming operations (such as uploading resources to the server), the broadcast recipient's life cycle is very short, to do time-consuming operation, it can be in the Receive method Open a service


14 Describe the relationship between the activity intent service

For example, to update data with the network. Activity can display the latest data, there is a service in the activity to request the latest data, and intent can open the service.

15. Please describe the broadcastreceiver.

The broadcast recipient is the object that receives the broadcast from the system and the application itself. such as the system switch machine, call SMS. The screen is light and dark .... Wait, there's a definition of radio.

Broadcast is divided into two orderly broadcasts and no broadcast, ordered broadcast is a synchronous operation, no broadcast is an asynchronous operation


Terminate a broadcast to call the Abortbroadcast method after receiving the broadcast, the designated broadcast recipient is not intercepted must be broadcast, (such as telephone interception, the phone is registered binding the recipient must be broadcast, if we want to intercept, only in the recipient of their own definition              c7> setresultdata (null); Resets the data to null. and cannot intercept so that the phone does not receive the broadcast.

Private class Myreceiver extends broadcastreceiver{


@Override
public void OnReceive (context context, Intent Intent) {
TODO auto-generated Method Stub

Setresultdata (NULL);
}

}

Sendstickybroadcast (Intent): This is a sticky broadcast, it also means that the haunting broadcast, such as an ordinary broadcast receiver, if we do not register, then will not receive the broadcast. A broadcast (the general life cycle of only 20 seconds, not receiving, then not receiving) and Sticiky is different we send a stickky broadcast, then this broadcast will stay for a period of time, such as mobile phone network broadcast on WiFi needs to initialize the network card, Receive network hotspot and so on, 20 seconds of time may not be enough, so change the status of the phone network here to use the sendstickybroadcast to ensure that the status of the NIC will be updated. (This method understands) WiFi settings.


There are generally two ways to register a broadcast recipient

One is to register in the manifest file: Register receiver Filter Intentfiler Once the application is deployed to the phone it will take effect (now you may need to start the application manually once, after the installation has not started as if it is not available, Android security optimization. )

One is the code registered registreceiver (receiver,filter) (code registration of the broadcast must be performed after the broadcast will take effect)

Send Custom Broadcasts

Intent Itent=new Intent ("Com.self.broadcast")

Sendbroadcast (Intent);

Differences between the two types of registrations:

Static registration is when the program is closed, if there is a broadcast sent, you can also start the program
The lifecycle of a dynamic registration is the same as the life cycle of a program, and a broadcast that is dynamically registered after a program is closed is not able to receive a broadcast

Advantages of dynamic registration: In the Android broadcast mechanism, the priority of dynamic registration is higher than the priority of static registration, so we need to dynamically register the broadcast receiver if necessary.
A bit of static registration: The dynamic registration of the broadcast receiver also has the advantage that when the activity used to register the broadcast is closed, the broadcast fails, and it also reflects one of the advantages of statically registered broadcasts, that there is no need to worry about whether the broadcast receiver is turned off or not, as long as the device is on, the broadcast receiver can receive it.

A summary of the most detailed and basic Android interview knowledge points in history (i)

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.