In the past has been in the major sites, the forum to see a variety of technical points and knowledge points, are required to use what technology points, to find relevant posts, never write their own hands;
Starting today, I set a goal for myself, will be used in the andorid of technical points and knowledge points are written down, to facilitate their work in the future encounter similar problems, can quickly find a solution------This paste will have a lot of knowledge of the content for the excerpt, and Bo Master own some understanding and views, For reference only, there is the wrong place to welcome the great God guidance.
Straight into the theme, when it comes to Android, don't say Android's four components
Four components in the Andorid
1.Activity (not explained)
2.Service (Service)
3.Broadcast receiver (broadcast receiver)
4.Content Provider (content Provider)
First, the Activity basic introduction
First, attach an activity's life cycle diagram (image to Baidu)
1. Start activity: The system calls the OnCreate (create) method first, then calls the OnStart (start) method, and finally calls Onresume (user-actionable).
2. Current activity is overwritten or locked by other activity: the system invokes the OnPause method, pausing the execution of the current activity.
3. The current activity is returned to the foreground or unlock screen by the overwritten state: The system calls the Onresume method and enters the running state again.
4. The current activity goes to the new activity interface or press the home key to return to the main screen, itself back to the background: the system will first call the OnPause method, and then call the OnStop method, into a stagnant state.
5. The user backs back to this activity: the system calls the Onrestart method first, then calls the OnStart method, and finally calls the Onresume method, again into the running state.
6. Current activity is in a covered state or the background is not visible, that is, the 2nd and 4th steps, the system is out of memory, kill the current activity, and then the user returned to the current activity: Call OnCreate method Again, OnStart method, Onresume method To enter a running state.
7. The user exits the current activity: The system calls the OnPause method first, then calls the OnStop method, and finally calls the Ondestory method to end the current activity.
This is the activity's most basic life cycle introduction, followed by a separate activity to explain the details of four startup modes, as well as various menu settings
----------------------------------------------------
Second, Service
The service is running in the background and does not interact with the user application component. Each service must be declared by <service> in manifest. Can be started by Contect.startservice and Contect.bindserverice.
Service can be used in multi-occasions, such as multimedia playback when the user started other activity this time the program to continue to play in the background, such as the detection of changes in the file on the SD card, or in the background to record your geographic information changes and so on, in short, the service is always hidden behind.
Service, like other application components, runs in the main thread of the process. This means that if the service requires a lot of time-consuming or blocking operations, it needs to be implemented in its child threads.
The two Modes of service (StartService ()/bindservice () are not completely detached)
Local Service is used inside the application.
It can start and run until someone stops it or it stops itself. In this way, it starts with a call to Context.startservice () and ends with a call to Context.stopservice (). It can call Service.stopself () or Service.stopselfresult () to stop itself. No matter how many times the StartService () method is called, you only need to call once StopService () to stop the service.
Some time-consuming tasks for implementing the application itself, such as querying the upgrade information, and not consuming the application such as the activity of the thread, but the single-threaded background execution, so the user experience is better.
Remote services are used between applications within the Android system.
It can be manipulated by its own defined and exposed interfaces. The client establishes a connection to the service object and invokes the service through that connection. The connection is established to call the Context.bindservice () method to call Context.unbindservice () to close. Multiple clients can bind to the same service. If the service is not loaded at this time, bindservice () loads it first.
Can be reused by other applications, such as the weather forecast service, other applications do not need to write such a service, call the existing can.
Third, broadcast receiver Broadcastreceiver broadcast receiver, mainly for the asynchronous reception of broadcast • Normal broadcast the regular broadcasts (sent with Context.sendbroadcast ()) is completely asynchronous. They all run in an undefined order, usually at the same time. This will be more efficient, but it means that receiver cannot contain the results you want to use or the API that is aborted.
• Ordered broadcast Ordered broadcasts (sent with Context.sendorderedbroadcast ()) is sent to one receiver at a time. Order is that each receiver can be transmitted to the next receiver after execution, or it can completely stop the transmission--not to other receiver. The order of receiver operation can be controlled by the android:priority inside the matched Intent-filter, and receiver runs in any order when priority is the same.
It is important to note that even if the normal broadcasts, the system may in some cases be restored to one receiver at a time. In particular, receiver may need to create a process that can only run one receiver at a time to avoid overloading the system.
Broadcast Receiver does not provide a visual interface to display broadcast information. You can use notification and notification Manager to visualize the interface of information, display the contents of broadcast information, icons and vibration information.
Life cycle
A Broadcastreceiver object is valid only if it is called OnReceive (Context, Intent), and when returned from the function, the object is invalid and ends the life cycle.
Therefore, it can be seen from this feature that in the OnReceive (Context, Intent) function that is invoked, there is no time-consuming operation that can be performed using a thread. For time-consuming operations, start service to complete. Because broadcastreceiver may be invalid when you get the results returned by other asynchronous operations.
Send broadcast
The broadcast of the event is simple, building a Intent object, and calling the Sendbroadcast (Intent) method to emit the broadcast. There are also Sendorderedbroadcast (), Sendstickybroadcast () and other methods, please consult API Doc.
1.new Intent with action name
Intent Intent = new Intent (String action);
Or just new Intent, and then
Intent.setaction (String action);
After the 2.set data is ready, in activity,
Sendbroadcast (Intent); Send broadcast
Receive broadcasts
Implemented by defining an inherited Broadcastreceiver class, inheriting the class, overwriting its Onreceiver method, and responding to the event in the method.
- public class Smsreceiver extends Broadcastreceiver {
- @Override
- public void OnReceive (context context, Intent Intent) {
- Get data from SMS intent
- Bundle bundle = Intent.getextras ();
- if (bundle! = null) {
- Get message by "PDUs"
- Object[] Objarray = (object[]) bundle.get ("PDUs");
- Rebuild SMS
- smsmessage[] messages = new Smsmessage[objarray.length];
- for (int i=0; i < objarray.length; i++) {
- Messages[i] = SMSMESSAGE.CREATEFROMPDU ((byte[]) objarray[i]);
- StringBuilder str = new StringBuilder ("From:");
- Str.append (Messages[i].getdisplayoriginatingaddress ());
- Str.append ("\nmessage:\n");
- Str.append (Messages[i].getdisplaymessagebody ());
- Toast.maketext (Context, str.tostring (), Toast.length_long)
- . Show ();
- }
- }
- }
- }
Register receiver
There are two ways of registering:
1. Statically, define receiver in the Androidmanifest.xml application and set the action to be received.
- <receiver android:name= ". Smsreceiver ">
- <intent-filter>
- <action android:name= "Android.provider.Telephony.SMS_RECEIVED"/>
- </intent-filter>
- </receiver>
Copy Code 2. Dynamic mode, the function is called in the activity to register, and static content is similar. One parameter is receiver and the other is Intentfilter, which is the action to receive.
- public class Hellodemo extends Activity {
- Private Broadcastreceiver receiver;
- @Override
- protected void OnStart () {
- Super.onstart ();
- Receiver = new Callreceiver ();
- Registerreceiver (receiver, New Intentfilter ("Android.intent.action.PHONE_STATE"));
- }
- @Override
- protected void OnStop () {
- Unregisterreceiver (receiver);
- Super.onstop ();
- }
- }
Copy code a receiver can receive multiple actions, that is, multiple intent-filter, and you need to judge Intent.getaction (action name) in OnReceive.
It is recommended to use the static registration method, the system to manage receiver, and all receiver in the program can be in the XML at a glance. The dynamic registration method, hidden in the code, is more difficult to find.
and dynamic registration, it is important to remember to call the Context.unregisterreceiver () method before exiting the program. Usually in the activity of the OnStart () to register, OnStop () inside to write off. The official reminder is that if you register in Activity.onresume (), you must log out of Activity.onpause ().
Permission permissions
To receive some action, you need to add the appropriate permission inside the Androidmanifest.xml. For example, receive SMS:
- <uses-permission android:name= "Android.permission.RECEIVE_SMS"/>
Copy the code below to give the Callreceiver code for the dynamically registered broadcast processing of incoming calls:
One way is to directly read the Intent.getstringextra ("Incoming_number") to get the call number:
- public class Callreceiver extends Broadcastreceiver {
- @Override
- public void OnReceive (context context, Intent Intent) {
- Telephonymanager Telemanager = (telephonymanager) context.getsystemservice (Context.telephony_service);
- Switch (telemanager.getcallstate ()) {
- Case telephonymanager.call_state_ringing://Bell
- Toast.maketext (Context, "ringing:" + Intent.getstringextra ("Incoming_number"), Toast.length_long). Show ();
- Break
- Case Telephonymanager.call_state_offhook://Answer
- Toast.maketext (Context, "Offhook:" + Intent.getstringextra ("Incoming_number"), Toast.length_long). Show ();
- Break
- Case Telephonymanager.call_state_idle://Hang off
- Toast.maketext (M_context, "Idle:" + Incomingnumber, Toast.length_long). Show ();
- Break
- }
- }
- }
Copy code at run time, found that in addition to the ring can obtain a call number, answer and hang up are not successfully obtained, displayed as null.
Another way is to listen for changes in state by Phonestatelistener oncallstatechanged:
- public class Callreceiver extends Broadcastreceiver {
- Private Context M_context;
- @Override
- public void OnReceive (context context, Intent Intent) {
- M_context = context;
- Telephonymanager Telemanager = (telephonymanager) context.getsystemservice (Context.telephony_service);
- Telemanager.listen (New Phonestatelistener () {
- @Override
- public void oncallstatechanged (int state, String incomingnumber) {
- Switch (state) {
- Case telephonymanager.call_state_ringing://Bell
- Toast.maketext (M_context, "ringing:" + incomingnumber, Toast.length_long)
- . Show ();
- Break
- Case Telephonymanager.call_state_offhook://Answer
- Toast.maketext (M_context, "Offhook:" + Incomingnumber, Toast.length_long)
- . Show ();
- Break
- Case Telephonymanager.call_state_idle://Hang off
- Toast.maketext (M_context, "Idle:" + Incomingnumber, Toast.length_long)
- . Show ();
- Break
- }
- }}, Phonestatelistener.listen_call_state);
- }
- }
The copy code runtime also found that Incomingnumber was taken as blank when answering and hanging.
This receiver is called 3 times because the state of the call is being monitored.
To listen for call status, add permissions:
- <uses-permission android:name= "Android.permission.READ_PHONE_STATE"/>
Copy Code ===========
Summary:
1. For Sendbroadcast Intent object, you need to set its action name;
2. It is recommended to use the explicit indication receiver, indicated in the configuration file androidmanifest.xml;
3. A receiver can receive multiple action;
4. Each receive broadcast will regenerate a receiving broadcast object, call OnReceive again;
5. Try not to deal with too many logic problems in broadcast, and suggest complex logic to the activity or Service to handle.
--------------------------------------------
Iv. Content Provider Detailed
ContentProvider (content Provider) is one of the four components of Android. Mainly used to share data externally, that is, by contentprovider the data in the application to other applications access, other applications can be contentprovider to the data in the specified application. ContentProvider are divided into systematic and customized systems, such as contacts, pictures and other data.
The data manipulation in Android includes:
File, Sqlite3, Preferences, Contectresolver and contentprovider the first three kinds of data operation methods are only for the data in this application, the program can not be used in these three ways to manipulate data in other applications.
Android provides Contectresolver and ContentProvider to manipulate data from other applications.
How to use:
An application implements ContentProvider to provide content to other applications to operate,
An app uses Contentresolver to manipulate other application data, but it can also be used in its own application.
The following is a general overview of ContentProvider in Google Docs:
The content provider uses some specific application data to feed other applications. The content provider inherits from the ContentProvider base class and implements a standard set of methods for other applications to fetch and store the data it manages. However, the application does not call these methods directly, but instead uses a Contentresolver object that invokes its method as an alternative. Contentresolver can work with any content provider to manage all relevant interactive communications.
1.ContentProvider
Android offers some of the main data types of contentprovider, such as audio, video, images, and personal contacts. Some Android-provided ContentProvider can be found under the Android.provider package. By obtaining these contentprovider, you can query the data they contain, as long as the appropriate read permissions have been obtained.
Main methods:
public boolean onCreate () is called when the ContentProvider is created
Public Cursor query (Uri, string[], String, string[], string) is used to query the ContentProvider of the specified Uri, returning a cursor
The public URI insert (URI, contentvalues) is used to add data to the ContentProvider of the specified URI
public int update (URI, Contentvalues, String, string[]) to update the data in the contentprovider of the specified Uri
public int Delete (Uri, String, string[]) to delete data from the ContentProvider of the specified Uri
Public String GetType (URI) used to return the MIME type of data in the specified Uri
* If the manipulated data belongs to the collection type, then the MIME type string should start with vnd.android.cursor.dir/.
For example: To get the URI for all person Records is Content://contacts/person, the MIME type string returned is "Vnd.android.cursor.dir/person".
* If the data to be manipulated belongs to non-collection type data, then the MIME type string should start with vnd.android.cursor.item/.
For example: To get the URI for the person record with ID 10 as CONTENT://CONTACTS/PERSON/10, the MIME type string returned should be "Vnd.android.cursor.item/person".
2.ContentResolver
When external applications need to add, delete, modify, and query the data in ContentProvider, you can use the Contentresolver class to get the Contentresolver object, You can use the Getcontentresolver () method provided by the context.
contentresolver cr = Getcontentresolver ();
The methods provided by Contentresolver and the methods provided by ContentProvider correspond to the following methods.
The public URI insert (URI uri, contentvalues values) is used to add data to the ContentProvider of the specified URI.
The public int Delete (URI Uri, String selection, string[] selectionargs) is used to delete data from the ContentProvider of the specified Uri.
The public int update (URI uri, contentvalues values, String selection, string[] selectionargs) is used to update the data in ContentProvider of the specified Uri.
Public Cursor query (URI uri, string[] projection, string selection, string[] Selectionargs, string sortOrder) for querying the CO of the specified Uri Ntentprovider.
3.Uri
The URI specifies the ContentProvider to be manipulated, in fact a URI can be considered as a URL, we divide the URI into three parts.
The first part is "content://". Can be viewed as the "http://" in the URL.
The second part is the hostname or authority, which uniquely identifies the contentprovider, and the external application needs to find it based on this identity. Can be viewed as the hostname in the URL, such as "blog.csdn.net".
The third part is the path name, which is used to represent the data that will be manipulated. Can be thought of as a broken-down content path in URLs.
---------------------------------
Android Basics-For beginners with Java Basics (four components)