Andorid Interview 4

Source: Internet
Author: User

Src/Java original code storage directory
GEN/automatically generate directory
The gen directory stores all files automatically generated by Android development tools. The most important part in the directory is the R. Java file. This file is automatically generated by the android development tool. The android development tool automatically updates and modifies the R. Java file based on the resources in the res directory. Because the R. Java file is automatically generated by the development tool, we should avoid manual modification to R. java. R. Java plays a dictionary role in the application. It contains the IDs of various resources. Through R. Java, the application can easily find the corresponding resources. In addition, the compiler checks the R. whether the resources in the Java list are used, and those that are not used are not compiled into the software. This can reduce the space occupied by applications on mobile phones.
Res/Resource Directory
In this directory, we can store various resources used by applications, such as XML interface files, images, and data. For details, see the remarks column below the PPT.
Assets Resource Directory
In addition to providing the/RES directory for storing resource files, android can also store resource files in the/assets directory, and the resource files in the/Assets Directory are not stored in the R. java automatically generates an ID. Therefore, the file path must be specified for reading files in the/assets directory, for example, file: // android_asset/xxx.3gp.
Androidmanifest. XML project list file
This file lists the functions provided by the application. You need to configure the components you have developed in this file, if the application uses built-in applications (such as telephone services, Internet services, SMS services, and GPS services), you must declare the permission in this file.
Default. properties project environment information, which generally does not need to be modified

In actual development, the process of developing Android software must be continuously tested. The JUnit testing framework is a required technology for formal Android development. components can be obtained in JUnit to simulate the correctness of event sending and detection program processing.
Step 1: First Add the following red code to androidmanifest. xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="cn.itcast.action“ android:versionCode="1“  android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name">        <uses-library android:name="android.test.runner" />        .... </application> <uses-sdk android:minSdkVersion="6" /> <instrumentation android:name="android.test.InstrumentationTestRunner"  android:targetPackage="cn.itcast.action" android:label="Tests for My App" /></manifest>

The package specified by targetpackage must be the same as the application package.
Step 2: Compile the unit test code (select the method to be tested, right-click "Run as" -- "android JUnit test "):

import android.test.AndroidTestCase;import android.util.Log;public class XMLTest extends AndroidTestCase {  public void testSomething() throws Throwable {  Assert.assertTrue(1 + 1 == 3);  }}

Most of the time, our software needs to store or re-access the processed data. Android provides the following methods for data storage:
File
Sharedpreferences (parameter)
SQLite Database
Content Provider)
Network

Context. mode_private: the default operation mode. This mode indicates that the file is private data and can only be accessed by the application itself. In this mode, the written content will overwrite the content of the original file, if you want to append the newly written content to the original file. You can use context. mode_append.
Context. mode_append: the mode checks whether the file exists and appends the content to the file if it exists. Otherwise, a new file is created.
Context. mode_world_readable and context. mode_world_writeable are used to control whether other applications have the permission to read and write the file.
Mode_world_readable: indicates that the current file can be read by other applications; mode_world_writeable: indicates that the current file can be written by other applications.
If you want the file to be read and written by other applications, you can pass in:
Openfileoutput ("itcast.txt", context. mode_world_readable + context. mode_world_writeable );

Androidhas a set of security models. When the application program (.apk) is installed, the system will assign a userid to it. When the application wants to access other resources, such as files, it needs to match the userid. By default, files created by any application, sharedpreferences, and databases, should be private (in/data/<package name>/files), and cannot be accessed by other programs. Unless context. mode_world_readable or context. mode_world_writeable is specified during creation, only other programs can access it correctly.

To open a file that is private to the application in the/data/<package name>/Files directory, you can use the openfileinput () method provided by activity.
Fileinputstream instream = This. getcontext (). openfileinput ("itcast.txt ");
Log. I ("filetest", readinstream (instream ));
For the readinstream () method, see the remarks below this page.

Or directly use the absolute path of the file:
File file = new file ("/data/CN. itcast. Action/files/itcast.txt ");
Fileinputstream instream = new fileinputstream (File );
Log. I ("filetest", readinstream (instream ));
Note: "cn. itcast. Action" in the file path above is the package of the application. When you write code, replace it with the package used by your own application.
Only applications that create a private file can access the file. If you want the file to be read and written by other applications, you can specify the context. mode_world_readable and context. mode_world_writeable permissions when creating the file.

Activity also provides the getcachedir () and getfilesdir () methods:
The getcachedir () method is used to obtain the/data/<package name>/cache directory.
The getfilesdir () method is used to obtain the/data/<package name>/Files directory.

To access sdcard in a program, you need to apply for the permission to access sdcard.
The permission to access sdcard in androidmanifest. XML is as follows:
<! -- Create and delete file permissions in sdcard -->
<Uses-Permission Android: Name = "android. Permission. mount_unmount_filesystems"/>
<! -- Write data to sdcard -->
<Uses-Permission Android: Name = "android. Permission. write_external_storage"/>

Sax is an XML parser with high resolution speed and low memory usage. It is suitable for Android and other mobile devices. An event-driven file is used to parse an XML file. That is to say, it does not need to parse a complete file. In the process of parsing a document in order of content, sax checks whether the currently read characters are valid for a part of the XML syntax. If yes, the event is triggered. The so-called events are actually some callback methods, which are defined in the contenthandler interface. Below are some common contenthandler interface methods:
Startdocument ()
When a document starts, call this method to perform preprocessing.
Enddocument ()
In contrast to the above method, when the document ends, you can call this method to do some aftercare work.
Startelement (string namespaceuri, string localname, string QNAME, attributes ATTS)
This method is triggered when a start tag is read. Namespaceuri is the namespace, localname is the tag name without the namespace prefix, and QNAME is the tag name with the namespace prefix. You can use ATTS to obtain all the attribute names and corresponding values. It should be noted that an important feature of Sax is its stream processing. When a tag is encountered, it will not record the previously encountered tag, that is, in startelement () all the information you know in the method is the name and attribute of the tag. As for the nested structure of the tag, the name of the Upper-layer tag, whether there is sub-meta, and other information related to the structure, they are all unknown, and they all need your program to complete. This makes it easier to program and process sax than Dom.
Endelement (string Uri, string localname, string name)
This method corresponds to the above method and calls this method when an end tag is encountered.
Characters (char [] CH, int start, int length)
This method is used to process the content read in the XML file. The first parameter is the file string content, and the next two parameters are the start position and length of the read string in this array, use new string (CH, start, length) to obtain the content.

Most of the time, the software we develop needs to provide users with the software parameter setting function, such as our commonly used QQ, users can set whether to allow strangers to add themselves as friends. For saving software configuration parameters, if the window software is used, we usually use the INI file for saving. If it is a j2se application, we will use the properties property file or XML for saving. For Android applications, how can we save software configuration parameters? The Android platform provides us with a sharedpreferences class, which is a lightweight storage class and is especially suitable for storing software configuration parameters. Use sharedpreferences to save data. xml files are used to store data in the/data/<package name>/shared_prefs directory:

Sharedpreferences = getsharedpreferences ("itcast", context. mode_private); Editor editor = sharedpreferences. edit (); // get the editor. putstring ("name", "Chuanzhi podcast"); Editor. putint ("Age", 4); Editor. commit (); // submit the modification

The content of the generated itcast. xml file is as follows:

<? XML version = '1. 0' encoding = 'utf-8' standalone = 'Yes'?> <Map> <string name = "name"> Chuanzhi podcast </string> <int name = "Age" value = "4"/> </map>

Because sharedpreferences uses an XML file to save data, the first parameter of the getsharedpreferences (name, mode) method is used to specify the name of the file. The name does not need a suffix, And the suffix will be automatically added by Android. The second parameter of the method specifies the file operation mode. There are four operation modes. the preceding four modes are described when you use the File mode to save data. If you want the XML file used by sharedpreferences to be read and written by other applications, you can specify the context. mode_world_readable and context. mode_world_writeable permissions.
In addition, activity provides another getpreferences (mode) method to operate sharedpreferences. By default, This method uses the Class Name of the current class without the package name as the file name.

The role of contentprovider in Android is to share data externally, that is, you can share the data in the application to other applications through contentprovider for access. Other applications can use contentprovider to add, delete, modify, and query data in your application. For data sharing, we have learned the file operation mode before. We know that the operation mode of a specified file is context. mode_world_readable or context. mode_world_writeable. So why use contentprovider to share data externally? If the file operation mode is used to share data externally, the Data Access Mode varies depending on the data storage mode, resulting in inconsistent data access methods, such: if an XML file is used to share data, XML parsing is required to read data. If sharedpreferences is used to share data, the sharedpreferences API must be used to read data.
The advantage of using contentprovider to share data externally is to unify the data access mode.
When an application needs to share data externally through contentprovider, the first step is to inherit contentprovider and override the following method:

public class PersonContentProvider extends ContentProvider{   public boolean onCreate()   public Uri insert(Uri uri, ContentValues values)   public int delete(Uri uri, String selection, String[] selectionArgs)   public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)   public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)   public String getType(Uri uri)}

The second step must be in androidmanifest. XML uses <provider> to configure the contentprovider. To allow other applications to find the contentprovider, The contentprovider uses authorities (host name/Domain Name) to uniquely identify it, you can regard contentprovider as a website (think about it, the website also provides data), and authorities is its domain name:

<manifest .... >    <application android:icon="@drawable/icon" android:label="@string/app_name">        <provider android:name=".PersonContentProvider" android:authorities="cn.itcast.providers.personprovider"/>    </application></manifest>

Multi-threaded file downloads allow you to download files faster. multi-threaded files are faster because they occupy a large amount of server resources. For example, if the server can serve a maximum of 100 users at the same time, one thread on the server corresponds to one user, and the other 100 threads are not executed concurrently in the computer, but are divided by the CPU into time slices for execution in turn, if app a uses 99 threads to download files, it is equivalent to occupying 99 user resources. Assume that the average execution time allocated by the CPU to each thread within one second is 10 ms, application A has a Ms execution time in one second on the server, while other applications only have 10 ms execution time in one second. Just like a tap, if the amount of water per second is equal, 990 ms of water is definitely more than 10 ms of water.
Multi-threaded download implementation process:
1> first get the length of the downloaded file, and then set the local file
.

Httpurlconnection. getcontentlength (); randomaccessfile file = new randomaccessfile ("qqwubisetup.exe", "RWD"); file. setlength (filesize); // you can specify the length of a local file.

2> calculate the Data Length and download location of each thread Based on the file length and thread count. For example, if the file length is 6 MB and the number of threads is 3, the data downloaded by each thread is 2 MB, as shown in.
3> use the range header field of HTTP to specify the position where each thread starts downloading the file and where the file is downloaded. For example, specify the position where the file is downloaded at 2 MB, download to location (4m-1byte), the Code is as follows:
Httpurlconnection. setrequestproperty ("range", "bytes = 2097152-4194303 ");
4> Save the file and use the randomaccessfile class to specify the position where each thread starts to write data to the local file.
Randomaccessfile threadfile = new randomaccessfile ("qqwubisetup.exe", "RWD ");
Threadfile. Seek (2097152); // from where the file is written

The bundle class is used to carry data. Similar to map, it is used to store values in the form of key-Value Name-value pairs. Compared with map, it provides various common types of putxxx ()/getxxx () methods, such as: putstring ()/getstring () and putint ()/getint (), putxxx () the getxxx () method is used to get data from the bundle object. The bundle actually uses the hashmap <string, Object> type variable to store the values put by the putxxx () method:

Public final class bundle implements parcelable, cloneable {...... map <string, Object> MMAP; Public bundle () {MMAP = new hashmap <string, Object> ();......} public void putstring (string key, string value) {MMAP. put (Key, value);} Public String getstring (string key) {object o = MMAP. get (key); Return (string) O ;........ // if the type conversion fails, null is returned. The processing code after the type conversion fails is omitted }}

When the getxxx () method of the bundle object is called, The method obtains data from the variable internally and converts the data type. The conversion type is determined by the xxx method, the getxxx () method returns the converted value.

Use the startactivityforresult (intent, int requestcode) method to open a new activity. We need to input a Request Code (the second parameter) for the startactivityforresult () method ). The value of the Request Code is set by the user according to the business needs, used to identify the request source. For example, a single activity has two buttons. Clicking these two buttons will open the same activity. No matter which button opens the new activity, when the new activity is closed, the system will call the onactivityresult (INT requestcode, int resultcode, intent data) method of the previous activity. In the onactivityresult () method, if you need to know that the new activity is opened by that button and want to handle the corresponding business, you can do this:
 

@ Override public void oncreate (bundle savedinstancestate ){.... button1.setonclicklistener (new view. onclicklistener () {public void onclick (view v) {startactivityforresult (new intent (mainactivity. this, newactivity. class), 1) ;}}); button2.setonclicklistener (new view. onclicklistener () {public void onclick (view v) {startactivityforresult (new intent (mainactivity. this, newactivity. class), 2) ;}}); @ override protected void onactivityresult (INT requestcode, int resultcode, intent data) {Switch (requestcode) {Case 1: // request from button 1 for corresponding business processing Case 2: // request from button 2 for corresponding business processing }}

The basic design concept of Android is to encourage the reduction of coupling between components. Therefore, Android provides intent (intent) and intent provides a general message system, it allows you to pass intent between your application and other applications to execute actions and generate events. Using intent, You can activate three core components of the Android app: Activity, service, and broadcast receiver.
Intent can be divided into explicit intent and implicit intent.
Explicit intent: Call intent. setcomponent () or intent. the setclass () method explicitly specifies the intent of the component name as the explicit intent, and the explicit intent specifies the component to which the intent should be passed.
Implicit intent: intent without explicitly specifying the component name is implicit intent. The Android system will find the most suitable component to process the intent based on the action, category, and data (Uri and data type) set in the implicit intent.

<intent-filter>     <action android:name="android.intent.action.CALL" />     <category android:name="android.intent.category.DEFAULT" />     <data android:scheme="tel" /></intent-filter><intent-filter>     <action android:name="android.intent.action.CALL" />     <category android:name="android.intent.category.DEFAULT" />     <data android:mimeType="vnd.android.cursor.item/phone" /></intent-filter>

 
Activity has three states:
When it is at the front-end of the screen (at the top of the current job stack), it is active or running. It is the activity that responds to user operations.
When there is another activity on it, it loses focus but is still visible to the user (such as the picture on the right), it is paused. The activity on it does not completely overwrite the screen or is transparent. The paused activity is still visible to the user, and it is a survival state (it retains all the status and member information and maintains a connection with the window manager ). If the system is in insufficient memory, the activity will be killed.
When it is completely overwritten by another activity, it is in the stopped state. It retains all status and member information. However, it is invisible to users, so its window will be hidden. If memory is needed elsewhere, the system will often kill this activity.
When an activity changes from one state to another, the following protection methods are called to notify the activity of this change:

void onCreate(Bundle savedInstanceState)void onStart()void onRestart()void onResume()void onPause()void onStop()void onDestroy()

These seven methods define the full lifecycle of an activity. Implementing these methods can help us monitor three nested lifecycles:

The full life cycle of an activity starts when oncreate () is called for the first time until ondestroy () is called. Activity sets all "Global" states in oncreate () to complete initialization, and releases all system resources in ondestroy. For example, if a thread of the activity is running in the background to download data from the network, it will create a thread in oncreate () and destroy the thread in ondestroy.

The visible life cycle of the activity starts from onstart () until the end of the corresponding onstop () call. During this period, the user can see the activity on the screen, although it may not be at the front-end or does not interact with the user. Between the two methods, we can reserve the resources required to display the activity to users. For example, if you no longer see what we display, you can register a broadcastreceiver in onstart () to monitor the changes that will affect the UI, but ignore it in onstop. The onstart () and onstop () methods can be called multiple times as the application is visible to the user.

The foreground life cycle of an activity starts from onresume () and ends with the onpause () call. During this period, the activity is located at the top of the foreground and interacts with the user. The activity changes the status frequently between pause and resume. For example, the onpause () method is called when the device is in sleep state or a new activity is started. The onresume () method is called when the activity gets the result or receives a new intent. For an example of the foreground life cycle, see the remarks column below the PPT.

The broadcast receiver (broadcastreceiver) is used to receive the broadcast intent. The broadcast intent is sent by calling context. sendbroadcast () and context. sendorderedbroadcast. Generally, a broadcast intent can be received by multiple broadcast recipients subscribed to this intent. This feature is similar to the topic Message Receiver in JMS. The method to implement a broadcast receiver is as follows:
Step 1: Inherit broadcastreceiver and override the onreceive () method.

public class IncomingSMSReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { }}

Step 2: subscribe to the broadcast intent you are interested in. There are two subscription methods:
First: Subscribe using code

IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");IncomingSMSReceiver receiver = new IncomingSMSReceiver();registerReceiver(receiver, filter);

Type 2: subscribe to the <Application> node in the androidmanifest. xml file:

<receiver android:name=".IncomingSMSReceiver">    <intent-filter>         <action android:name="android.provider.Telephony.SMS_RECEIVED"/>    </intent-filter></receiver>

In Android, each time a broadcast message arrives, A broadcastreceiver instance is created and the onreceive () method is executed. After the onreceive () method is executed, the broadcastreceiver instance is destroyed. When the onreceive () method is not completed within 10 seconds, Android considers the program to be unresponsive. Therefore, you cannot perform some time-consuming operations in broadcastreceiver. the ANR (application No Response) dialog box is displayed on the other side. If you need to complete a time-consuming task, you should send intent to the service, which is done by the Service. Subthreads cannot be used here, because the life cycle of broadcastreceiver is very short, and the subthread may end before it ends. Once broadcastreceiver ends, the process where broadcastreceiver is located is easily killed first when the system requires memory because it is a blank process (process without any active components ). If its host process is killed, the working sub-thread is also killed. Therefore, it is unreliable to use sub-threads.

Services in Android and windows are similar. services generally do not have user operation interfaces. They run in a system and are not easily noticed by users. You can use them to develop programs such as monitoring. Service development is relatively simple, as follows:
Step 1: Inherit the service class
Public class smsservice extends Service {}

Step 2: configure the service on the <Application> node in the androidmanifest. xml file:
<Service android: Name = ". smsservice"/>

The service cannot run on its own. You must call the context. startservice () or context. bindservice () method to start the service. Both methods can start the service, but their usage is different. The startservice () method is used to enable the service. There is no relation between the visitor and the service. Even if the visitor exits, the Service continues to run. The bindservice () method is used to enable the Service. When a visitor is bound to the service, the service is terminated once the visitor exits. This feature features that the visitor does not want to live at the same time and must die at the same time.

Start the service using the context. startservice () method. You can only call the context. stopservice () method to end the service. The ondestroy () method is called when the service ends.

The service life cycle is related to the method used to start the service:
When the context. startservice () method is used to start the service, the related life cycle method oncreate ()? Onstart ()? Ondestroy ()
Oncreate () This method is called when a service is created. This method is called only once. No matter how many times the startservice () or bindservice () method is called, the service is created only once.
Onstart () calls back this method only when the context. startservice () method is used to start the service. This method is called when the service starts running. Although the startservice () method is called multiple times, the onstart () method is called multiple times.
Ondestroy () is called when the service is terminated.
When the context. bindservice () method is used to start the service, the related lifecycle Method
Oncreate ()? Onbind ()? Onunbind ()? Ondestroy ()
Onbind () calls back this method only when the context. bindservice () method is used to start the service. This method is called when the caller binds to the service. When the caller and the service are already bound, multiple calls to the context. bindservice () method will not cause this method to be called multiple times.
Onunbind () calls back this method only when the context. bindservice () method is used to start the service. This method is called when the caller and the service are unbound.
If you use the startservice () method to start the service, then call the bindservice () method to bind to the service, then call the unbindservice () method to unbind, and finally call the bindservice () method to bind to the service again, the method for triggering the lifecycle is as follows:
Oncreate ()? Onstart ()? Onbind ()? Onunbind () [true must be returned for the method after the overload]? Onrebind ()

 
Android provides two types of animations:
1> tween animation: implements the animation effect by performing a series of graphic transformations (including pan, zoom, rotate, and change transparency) on The View content. You can use XML or encoding to define the animation effect. There are four types of tween animation:

2> Frame Animation, that is, playing images prepared in advance in sequence, is similar to playing a film. Development steps:
(1) Put the prepared images under the Res/drawable project.
(2) Create the anim folder under the res directory of the project, and then define the animation XML file under the anim folder. The file name can be customized. Of course, you can also use the encoding method to define the animation effect (using the animationdrawable class ).
(3) bind an animation effect to the view control. Call the START () method that represents the animation's animationdrawable to start the animation.

In addition to using Sax to parse XML files, you can also use the familiar Dom to parse XML files. When the DOM parses an XML file, all the content of the XML file is stored in the memory in the form of a document tree. Then, you can use the dom api to traverse the XML tree and retrieve the required data. The code that uses Dom to operate XML looks intuitive, and it is easier to code than to implement it based on sax. However, because the Dom needs to store all the content of the XML file in the memory as a document tree, the memory consumption is relatively large, especially for mobile devices running Android, because the resources of devices are precious, we recommend that you use SAX to parse XML files. Of course, Dom is also feasible if the content of XML files is small.
In addition to using sax or Dom to parse XML files, you can also use the android built-in pull parser to parse XML files. The pull parser is an open-source Java project that can be used for both Android and javaee. If it is used in javaee, you need to put its JAR file into the class path. Because android has already been integrated into the pull parser, no JAR file needs to be added. XML files used by the Android system are parsed using the pull parser. The Running Method of the pull parser is similar to that of the SAX Parser. It provides similar events, such as the start element and end element events. You can use parser. Next () to enter the next element and trigger the corresponding event. Unlike sax, the events generated by the pull parser are numbers rather than methods. Therefore, you can use a switch to process events of interest. When parsing an element, call parser. nexttext () to obtain the value of the next text node.

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.