Android interview questions-short answer (1)

Source: Internet
Author: User

1. In multi-Thread programming, Handler, Thread, and Runnable classes are often used. Do you have figured out the relationship between them?

A: The minimum unit of CPU allocation for Android is a Thread. Handler is generally created in a Thread. Therefore, Handler and Thread are bound to each other and correspond to each other one by one. Runnable is an interface and Thread is a subclass of Runnable. Therefore, both of them are considered a process. As the name implies, HandlerThread is a thread that can process message loops. It is a thread with logoff and can process message loops. Instead of binding a Handler to a thread, it is better to say that Handler is one-to-one correspondence with logoff. In the UI thread (main thread): mHandler = new Handler ();

MHandler. post (new Runnable (){

Void run (){

// Execute the code ...}

});

This thread is actually running within the UI thread, and there is no new thread.

The common method for creating a thread is:

Thread thread = new Thread ();

Thread. start ();

HandlerThread thread = newHandlerThread ("string ");

Thread. start ();

2. How to set an application as a system-level application?

A: apk get system permissions; how to get the following: explain connection: http://blog.csdn.net/superkris/article/details/7709504

The first method is simple, but it needs to be compiled using make in the environment of the Android system source code:

1. Add the android: sharedUserId = "android. uid. system" attribute to the manifest node in AndroidManifest. xml of the application.

2. Modify the Android. mk file and add LOCAL_CERTIFICATE: = platform.

3. Use the mm command to compile the generated apk and you will have the permission to modify the system time.

The second method is to directly use the system signature file to sign the apk compiled by eclipse.

1. Add the android: sharedUserId = "android. uid. system" attribute.

2. Compile the apk file using eclipse.

3. Use the platform key of the target system to re-sign the apk file. First, find the key file. In the my ndroid source code directory, the location is "build/target/product/security", and the following two files are platform. pk8 and platform. x509.pem. Then use the Signapk tool provided by Android to sign the signapk. The source code of signapk is under "build/tools/Signapk", after compilation, under out/host/linux-x86/framework, use java-jarsignapk. jar platform. x509.pem platform. pk8 input.apk output.apk ".

Add the android: sharedUserId = "android. uid. system" attribute. With the Shared User id, multiple APK with the same User id can be configured to run in the same process. Then, assign the UID of the program to android. uid. system, that is, to allow the program to run in the system process, so that you have the permission to modify the system time.

It is not enough to add the UID. If the APK cannot be installed at this time, the system prompts that the signature is inconsistent because the program wants to run in the system process and the platform key of the target system is required, the platform mentioned in the second method above. pk8 and platform. x509.pem files. The apk can be put into the system process only after the two keys are signed. Adding LOCAL_CERTIFICATE: = platform to the first method is actually using the two keys for signature.

There is also a problem, that is, the program generated in this way can only be used in the original Android system or a self-compiled system, because such a system can get the platform. pk8 and platform. x509.pem files. If other companies do not even install Android. Try the original Android key for signature. The program runs OK on the simulator, but the prompt "Package... has no signatures that match those in shared user android. uid. system ", which also protects the system security.

3. Talk about the Android IPC (inter-process communication) Mechanism

A: http://blog.csdn.net/luoshengyang/article/details/6618363

In the Android system, every application is composed of activities and services. These activities and services may run in the same process or in different processes, android's IPC Mechanism is the Binder Mechanism. The Android system is based on the Linux kernel, and the Linux kernel inherits and is compatible with a wide range of Unix system inter-process communication (IPC) mechanisms. However, the Android system uses the Binder Mechanism instead of the various inter-process communication mechanisms mentioned above. The Binder is an inter-process communication mechanism, which is similar to the COM and CORBA distributed component architecture, in other words, the Remote Procedure Call (RPC) function is provided. In terms of English text, the Binder has the meaning of Binder, so what does it bond together? In the Binder Mechanism of the Android system, a system component is composed of Client, Server, Service Manager, and Binder drivers. The Client, Server, and Service Manager run in the user space, the kernel space of the Binder driver program. Binder is a Binder that binds these four components together. The core component is the Binder driver, and Service Manager provides the auxiliary management function, the Client and Server communicate with the Client-Server on the infrastructure provided by the Binder driver and ServiceManager;

1. Client, Server, and Service Manager are implemented in the user space. The Binder driver is implemented in the kernel space.

2. The Binder driver and Service Manager have been implemented on the Android platform. Developers only need to implement their own Client and Server in the user space.

3. The Binder Driver provides the device file/dev/binder to interact with the user space. The Client, Server, and Service Manager communicate with the Binder driver through the open and ioctl file operation functions.

4. inter-process communication between Client and Server is indirectly implemented through the Binder driver

5. Service Manager is a daemon for managing the Server and providing the Client with the ability to query the Server interface.

4. How apk is installed and uninstalled

A:Http://blog.csdn.net/lizhiguo0532/article/details/7077432

Http://www.itivy.com/android/archive/2011/8/10/android-apk-setup-method-and-principles.html

You can install APK in the following ways:
1. Install the system application. Check the system application at startup. If the system application is not installed, the installation will be skipped and there will be no installation interface.
2. download and install the application on the Internet. The installation is completed through the market application and there is no installation interface.
3. Install the ADB tool without the installation interface.
4. Install apks through sdks. The packageinstaller.apk application processes the installation and uninstallation processes.

Application installation involves the following directories:
The system/app system's built-in applications cannot be deleted.
The directory where data/app user programs are installed. You have the permission to delete them.
Data/data stores Application data
Data/dalvik-cache: Install the dex file in the apk to the dalvik-cache directory.
(The dex file is an executable file of the dalvik Virtual Machine. Its size is about 1/4 of the size of the original apk file)

Installation Process: copy the APK installation package to the data/app directory, decompress and scan the installation package, and save the dex file (Dalvik bytecode) to the dalvik-cache directory, and create the corresponding application data directory under the data/data directory.

Uninstall process: delete the files and directories created under the preceding three directories during installation.

5. How to Adapt 1) android has four different folders: H, L, M, X, and XX to store images of different resolutions. The system automatically Loads

2) You can set the Offset d in The dimens. xml file in the values-hpdi, values-mdpi, and values-ldpi folders.

It is worth mentioning that:

40dp

-14dp

The negative number is totally effective, and the system will think it is a negative value.

3) major mobile phone manufacturers make more or less changes to the Android operating system. Of course, these changes will have some impact on our applications.

For example:

(1) package name of the aidl file connecting to the music service in the system source code: com. android. music

(2) LG may modify the package where the aidl file is located (for example, to com. android. music. player), and modify the file content (add a method, reduce a few methods, or modify the method name). Then, if our application wants to publish on LG's mobile phone, then we must change the aidl file to be connected, which must be exactly the same as that modified by the LG manufacturer.

6. Whether or not apk decompilation is performed. How to Prevent decompilation:

Android decompilation Tool

· Dex2jar + jdgui

· Apktool

Prevent decompilation:

· Code encryption

In this way, you can only think about it. Once you encrypt it yourself, the Android system does not know you. How can you run it? (If so, it is probably the love encryption pushed by eoe ).

· Code obfuscation

In this way, I am not willing to classify him as preventing decompilation. From the Android and Java compilation principles, obfuscation and other operations on my own code will inevitably prevent the fact of decompilation. What he can do is to confuse characters and functions into a, B, c, d, 1, 2, 3, and so on.

This method is generally called,
Blocking reading, viewing, and understanding of decompiled code

Android mainly targetsProguard. cfg.

The specific implementation of this Part has been explained too much on the Internet, so I will not detail it here.

· Dynamic loading class

This method is inspired by the web terminal. If you want to prevent the Web end from being released.

So we can leave our important source code on the server, and load important classes through the DexClassLoader class if necessary. To prevent the core code from being decompiled.

See the DexClassLoader example for details.

· Use NDK to develop core code

As you can see above, it is difficult to disassemble compiled languages such as C/C ++. Therefore, we can safely use NDK for development and generate the SO library file before calling it.

PS:If some resource files are very precious, you can use # include to directly compile them into the library (of course, the memory may be large). You can consider this method on your own.

7. Android animation classification and explanation of the two types of animations

Tween animation

Also known as "intercept Animation" and "intercept Animation", the earliest contact with the Tween class was that the class Tween was used when I was learning Flash and performing animations using ActionScript.

TweenThe main function of an animation is to set the trajectory of the animation before it is drawn, including the time, position, and so on. However, the disadvantage of Tween animation is that it can only set the start and end frames. The intermediate process is completed by the system. Therefore, it is not used in Game Development with a large number of frames.
Tween provides a total of 4 animation Effects

Scale: Scaling Animation
Rotate: rotating Animation
Translate: Mobile Animation
Alpha: transparent gradient Animation

Frame Animation

Also known as frame animation, the main display mode is the animation's total tag, where Frame Animation is placed Tags, that is, several The frame combination of tags is frame animation. In the tag, android: oneshot = "false" is a very important attribute. The default value "false" indicates that the animation is played cyclically. If this parameter is set to "true", the animation is played only once. The tag records the information of each frame. android: drawable = "@ drawable/a" indicates that the image used for this frame is "a", and so on. Android: duration = "100" indicates that this frame lasts for 100 milliseconds. You can adjust the animation playback speed based on this value.

8. AIDL Full name: how to handle the data? Answer: The full name of AIDL is Android Interface Define Language.
When process A is going to call the service in process B and implement communication, we usually operate through AIDL.
Project:
First, create a RemoteService. aidl file in the net. blogjava. mobile. aidlservice package. In this file, you can customize an interface that contains the get method. The ADT plug-in will automatically generate a RemoteService. java file under the gen Directory, which contains an internal class named RemoteService. stub, which contains the get method of the aidl file interface.
Description 1: the location of the aidl file is not fixed and can be arbitrary.
Then define your own MyService class. In the MyService class, define an internal class to inherit the internal class RemoteService. stub and implement the get method. The onBind method returns the object of this internal class. The system will automatically encapsulate this object as an IBinder object and pass it to its caller.
Configure the MyService class in the AndroidManifest. xml file. The Code is as follows:







Why do you need to specify the ID of the AIDL service to be called, that is, to tell the outside world that the MyService class can be accessed by other processes, as long as other processes know this ID, it is precisely with this ID, project B can find Project A to implement communication.
Note: AIDL does not require permissions.
Project B:
First, we need to copy the RemoteService. java file generated in Project A to Project B and bind the aidl service to the bindService method.
Binding the AIDL Service uses the RemoteService ID as the intent action parameter.
NOTE: If we put the RemoteService. aidl file in a bag separately, copy the package under the gen directory to Project B. If we set the RemoteService. aidl files are stored together with other classes, so we need to create corresponding packages in Project B to ensure RmoteService. the java file registration is correct. We cannot modify RemoteService. java files
BindService (newInten ("net. blogjava. mobile. aidlservice. RemoteService"), serviceConnection, Context. BIND_AUTO_CREATE );
The service parameter in the onServiceConnected (ComponentName, IBinderservice) method of ServiceConnection is the object that inherits the internal class of RemoteService. stub in MyService class of Project. 9. Under what circumstances does GC occur in the Android system?

1. The database cursor is not closed

2. When constructing the adapter, the cache contentview is not used
Derivation of listview optimization problems-reduce the creation of view objects, make full use of contentview, you can use a static class to optimize the process of processing getview/

3. Use recycle () to release the memory when the Bitmap object is not in use

4. the lifecycle of objects in the activity is greater than that of the activity.
Debugging method: DDMS ==> HEAPSZIE ==> dataobject ==> [TotalSize]

10. What will cause Force Close? How to avoid it? Can I capture exceptions that cause them?
A: Generally, it is like a null pointer. You can check the logcat, and then correspond to the program to Solve error 11, activity's four modes, and the role of different modes. Http://blog.csdn.net/zhangjg_blog/article/details/10923643

Activity has four startup modes: standard, singleTop, singleTask, and singleInstance. To use these four startup modes, you must configure them in the launchMode attribute of the tag in the manifest file, for example:

Android: label = "@ string/interstitial_label"
Android: theme = "@ style/Theme. Dialog"
Android: launchMode = "singleTask"
Standard

Standard start mode is also the default start mode of activity. In this mode, the started activity can be instantiated multiple times, that is, instances of multiple activities can exist in the same task, and each instance processes an Intent object. If Activity A is started in standard mode and A is started, start Activity A again in A, that is, call startActivity (new Intent (this,. class), A new instance of A will be started on top of A, that is, the status of the current worker is A -->.

SingleTop

If an instance of the activity started in singleTop mode already exists in the worker top of the task, when the Activity is started again, no new instance will be created, but the instance located at the top of the stack will be reused, the onNewIntent () method of the instance is called to pass the Intent object to the instance. For example, if the Startup Mode of A is singleTop and an instance of A already exists in the top of the stack, call startActivity (new Intent (this,. class) when A is started, the instance A is not created again, but the original Instance is reused and the onNewIntent () method of the original Instance is called. This is the task worker or there is an instance of.

If an instance of the activity started in singleTop mode already exists in the same job as the worker task but is not on the top of the worker node, multiple instances will be created in the same behavior and standard mode.

SingleTask

According to Google's official documentation, if the Startup Mode of an activity is singleTask, the system will always start the activity at the bottom of a new task (root, other activities started by this activity will coexist with this activity in this new task. If such an activity already exists in the system, the instance will be reused and Its onNewIntent () method will be called. That is, such an activity only has one instance in the system.

In fact, this statement in the official documentation is not accurate. The activity in the startup mode of singleTask does not always start a new task. For details, refer to unlocking the "singleTask" Mystery of the Android Application Component Activity, which will also be verified through examples later in this article.

SingleInstance

It is always enabled in a new task and only one instance exists in the new task. That is to say, other activities started by the instance will automatically run in another task. When the activity instance is started again, existing tasks and instances are reused. The onNewIntent () method of the instance is called to pass the Intent instance to the instance. Like singleTask, only one such Activity instance exists in the system at the same time.

12. What is NDK?

NDK: NativeDevelopment Kit

AndroidNDK is a tool set that allows developers to embed components written in local code in Android applications.

The Android Application runs on the Dalvik virtual machine. NDK allows developers to use local code languages (such as C and C ++) to implement some functions of an application. In this way, code can be reused to provide convenience for a certain type of applications and improve the running speed in some cases (thanks to my wife for help ).

13. Differences between the permission for running Android programs and the permission for the file system answer: Permission for running Dalvik (permission for android)
File System linux kernel authorization

14. What is the 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 setting the Activity's android: configChanges = "orientation | keyboardHidden", the split screen will not re-call each lifecycle, but will only execute the onConfigurationChanged Method 15. How to set the Android Application as a system application

1. Add your app to the packages/apps/directory of the android source code and add the Android. mk file.
2. Add the android: sharedUserId = "android. uid. system" attribute to the manifest node in AndroidManifest. xml of the application.
3. Modify the Android. mk file and add LOCAL_CERTIFICATE: = platform.
4. Use the mm command to compile the generated apk with the same permissions as the system.
5. Use make snod In the android root directory to regenerate system. img
6. Start emulator and run the application to check whether the application is ready.

16. How to publish the SQLite database (dictionary. db file) with the apk file? You can copy the dictionary. db file to the res aw directory of the Eclipse Android project. All files in the res aw directory will not be compressed, so that files in the directory can be extracted directly. You can copy the dictionary. db file to the res aw directory.
17. How can I open the database files in the res aw directory?
A: In Android, you cannot directly open the database file in the resaw directory. Instead, you need to copy the file to a directory in the memory or SD card of your mobile phone when the program is started for the first time, then open the database file. The basic method of copying is to use the getResources (). openRawResource method to obtain the resource InputStream object in the res aw directory, and then write the data in the InputStream object to the corresponding file in other directories. You can use SQLiteDatabase. openOrCreateDatabase In the Android SDK to open SQLite database files in any directory. 18. Differences between wait and sleep in threads answer: wait releases the thread lock. sleep is not a thread lock and wait does not occupy system resources. sleep occupies resources.

19. The two methods register broadcaseReceiver and their differences.

A: What is the difference between dynamic registration and static registration of a BroadcastReceiver:

Dynamic Registration is more flexible than static registration. Experiments show that when you register a BroadcastReceiver statically, no matter whether the application is started or not. Can accept the corresponding broadcast.

During dynamic registration, if you do not execute the unregisterReceiver (); Method to cancel registration, it is the same as static. However, if you execute this method, you will not be able to accept the broadcast after it is executed.

20. In android, briefly describe the jni call process.

1) install and download Cygwin and Android NDK
2) Design of the jni interface in the ndk Project
3) use C/C ++ to implement local methods
4) JNI generates the dynamic link library. so file
5) copy the dynamic link library to the java project, call it in the java project, and run the java project.
21. Briefly describe the Android Application structure?

The Android Application structure is:
Linux Kernel (Linux Kernel ),

Libraries (system Runtime library or c/c ++ core library ),

Application Framework (Development Framework Package ),

Applications (core Applications)
22. inherit the SQLiteOpenHelper implementation:

1) create a "diaryOpenHelper. db" database with version 1,
2). Create a "diary" table (including a _ id Primary Key and auto-increment, topic category 100
Length, content Encoding type 1000 length)
3) when the database version changes, delete the diary table and recreate the diary table.

Publicclass DBHelper extendsSQLiteOpenHelper {

Public final static String DATABASENAME = "diaryOpenHelper. db ";
Public final static int DATABASEVERSION = 1;

// Create a database
Public DBHelper (Context context, Stringname, CursorFactory factory, int version)
{
Super (context, DATABASENAME, factory, DATABASEVERSION );
}
// Create institutional files such as tables
Public void onCreate (SQLiteDatabase db)
{
String SQL = "create tablediary" +
"(" +
"_ Idinteger primary key autoincrement," +
"Topicvarchar (100)," +
& Quot; contentvarchar (1000) & quot; +
")";
Db.exe cSQL (SQL );
}
// Call this method if the database version is updated.
Public void onUpgrade (SQLiteDatabasedb, int oldVersion, int newVersion)
{

String SQL = "drop table ifexists diary ";
Db.exe cSQL (SQL );
This. onCreate (db );
}
}

23. The ProgressBar control is available on the page. Use the writing thread to display the progress in 10 seconds.
Publicclass ProgressBarStu extends Activity {

Private ProgressBar progressBar = null;
Protected void onCreate (BundlesavedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. progressbar );
// From here to below is the key
ProgressBar = (ProgressBar) findViewById (R. id. progressBar );

Thread thread = new Thread (newRunnable (){

@ Override
Public void run (){
Int progressBarMax = progressBar. getMax ();
Try {
While (progressBarMax! = ProgressBar. getProgress ())
{

IntstepProgress = progressBarMax/10;
Intcurrentprogress = progressBar. getProgress ();
ProgressBar. setProgress (currentprogress + stepProgress );
Thread. sleep (1000 );
}

} Catch (InterruptedException e ){
// TODO Auto-generatedcatch block
E. printStackTrace ();
}

}
});

Thread. start ();

// Key end
}

}
24. Describe the lifecycle of an Activity.

Three required methods: onCreate ()-- (1) The parent Activity starts the Activity and the Child Actvity exits. The Calling sequence of the parent Activity is as follows:
AAA -- <onResume () -- <onPause () -- <onStop ()-- (2) The user clicks Home and the Actvity call sequence is as follows:
AAA -- <onResume () -- <onPause () -- <onStop () -- Maybe -- (3) Call finish (). The Activity call sequence is as follows:
AAA -- <onPause () -- <onStop () -- <onDestroy ()
(4) display dialog on the Activity. The call sequence of the Activity is as follows:
AAA
(5) display transparent or non-full screen Activity on the parent activity. The call sequence of the Activity is as follows:
AAA -- <onResume () -- <onPause ()
(6) the device enters the sleep state. The Activity call sequence is as follows:
AAA -- <onFreeze () -- <onPause ()
25. If the background Activity is recycled by the system for some reason, How can I save the current status before being recycled by the system?

Write the following statement in oncreate to get the Saved state:

1.If(SavedInstanceState! =Null

2. & savedInstanceState. getInt ("currentposition ")! = 0 ){

3.

4. videoView. seekTo (savedInstanceState. getInt ("currentposition "));

5 .}

Override this method to save the status

6.Protected voidOnSaveInstanceState (Bundle outState ){

7. // TODO Auto-generated method stub

8. outState. putInt ("currentposition", videoView. getCurrentPosition ());

9. Log. v ("tag", "onSaveInstanceState ");

10.Super. OnSaveInstanceState (outState );

11 .}


When one Activity A in your program is running, it actively or passively runs another Activity B. At this time, A will execute onSaveInstanceState (). B will come to A again after it is completed. There are two situations at this time: A is recycled, and A is not recycled. A will call onCreate () again when it is recycled () the method is different from the method in which the savedInstanceState parameter is included in onCreate (). If it is not recovered, the onResume () is executed directly and the onCreate () is skipped.
26. How to set an Activity as a window style.

In AndroidManifest. android: theme = "@ android: style/Theme. dialog "or android: theme =" @ android: style/Theme. translucent "becomes Translucent
27. How to exit the Activity? How can I safely exit the Application that has called multiple activities?

For a single Activity application, it is easy to exit. Simply finish.
Of course, you can also use methods such as killProcess () and System. exit.

28. introduce how ContentProvider achieves data sharing.

Create a Content provider of your own or add your data to an existing Contentprovider, provided that you have the same data type and the permission to write to Contentprovider.

29. Explain the relationship among Message, Handler, MessageQueue, and logoff in the single-thread model.

Handler introduction:
A Handler allows you to send and process Message and Runable objects, which are associated with the MessageQueue of a thread. Each thread instance is associated with a separate thread and the MessageQueue of the thread. When you create a new Handler, it is bound with the thread that created it. Here, we can also understand the thread as the MessageQueue. From this point of view, Handler passes the Message and Runable objects to MessageQueue, and when these objects leave MessageQueue, Handler is responsible for executing them.

Handler has two main purposes:

(1) determine to execute one or more Message and Runnable objects at a certain time point in the future.

(2) Add some actions to be executed in other threads (not Handler binding threads.

Scheduling Message, that is, (1), can be completed using the following methods:
Post (Runnable): Runnable is executed on the thread bound to handler, that is, no new thread is created.
PostAtTime (Runnable, long ):
PostDelayed (Runnable, long ):
SendEmptyMessage (int ):
SendMessage (Message ):
SendMessageAtTime (Message, long ):
SendMessageDelayed (Message, long ):
The post action allows you to queue Runnable objects into MessageQueue. When MessageQueue receives these messages, execute them, of course, in a certain order. The sendMessage action allows you to queue Message objects. These Message objects contain some information. Handler's hanlerMessage (Message) processes these messages. of course, handlerMessage (Message) must be overwritten by the sub-class of Handler. This is what programmers need to do.

When posting or sending is sent to a Hanler, you can perform the following three actions: When MessageQueue is ready, it will process the request, define a delay time, and define a precise time for processing. The latter two allow you to implement timeout, tick, and time-based behaviors.

When your application creates a new process, the main thread (that is, the UI thread) comes with a MessageQueue, which manages the top-level application objects (such as activities and broadcastreceivers) and the form created by the main thread. You can create your own thread and communicate with the main thread through a Handler. This is done through post and sendmessage, just like before. The difference is in which thread to execute this method. When appropriate, the given Runnable and Message will be Scheduled in the MessageQueue of Handler.


Message introduction:
The Message class defines an information that contains a descriptor and any data object. This information is used to pass to Handler. the Message Object provides two additional int fields and one Object field, which allows you to skip the allocation action in most cases.
Although the Message constructor is public, the best way to obtain the Message instance is to call Message. obtain (), or Handler. obtainMessage () method. These methods obtain one from the recycle Object pool.


MessageQueue introduction:
This is an underlying class that contains the message list. Logoff is responsible for distributing these messages. Messages are not directly added to a MessageQueue, but are associated with logoff through MessageQueue. IdleHandler.
You can obtain MessageQueue from the current thread through logoff. myQueue.


Logoff introduction:
The logoff class is used to execute the message loop in a thread. By default, no message loop is associated with a thread. In the thread, call prepare () to create a logoff, and then use loop () to process the messages until the loop ends.

Most of the interactions with message loop are handled by Handler.

The following is a typical thread implementation with logoff.
Class LooperThread extends Thread {
Public Handler mHandler;

Public void run (){
Logoff. prepare ();

MHandler = new Handler (){
PublicvoidhandleMessage (Message msg ){
// Processincomingmessages here
}
};

Logoff. loop ();
}
}
30. If multiple browsers are installed on the system, can you specify a browser to access the specified page? Describe the reason.

Directly send the Uri to pass the parameter, or use the data attribute in intentfilter in manifest.

31. What is ANR and how to avoid it?

ANR: ApplicationNotResponding, 5 seconds

In Android, the activity manager and window manager system services are responsible for monitoring application responses. Android displays the ANR dialog box when the following conditions occur:

Response to input events (such as buttons and touch screen events) exceeds 5 seconds

The intentReceiver has not been executed for more than 10 seconds.

Android applications run completely in an independent thread (such as main ). This means that any operation that runs in the main thread requires a large amount of time will lead to ANR. At this time, your application has no chance to respond to input events and Intentbroadcast ).

Therefore, any method running in the main thread should do as little work as possible. This is especially true for important methods in the activity lifecycle, such as onCreate () and onResume. Potential time-consuming operations, such as accessing networks and databases, or computing with high overhead, such as modifying the bitmap size, must be completed in a separate sub-thread (or using asynchronous requests, such as database operations ). However, this does not mean that your main Thread needs to enter the blocking state and has waited for the sub-Thread to end -- nor does it need to call the Therad. wait () or Thread. sleep () method. Instead, the main thread provides a Handler for the sub-thread so that the sub-thread can call it at the end of the day (xing: see the Snake example, this method is different from what we used previously ). Using this method involves your application, which ensures that your program responds well to the input and avoids the ANR generated because the input event is not processed for more than five seconds. This practice needs to be applied to all the threads that display the user interface, because they all face the same timeout problem.

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.