Android Basics-For beginners with Java Basics (four components)

Source: Internet
Author: User

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.
  1. public class Smsreceiver extends Broadcastreceiver {
  2. @Override
  3. public void OnReceive (context context, Intent Intent) {
  4. Get data from SMS intent
  5. Bundle bundle = Intent.getextras ();
  6. if (bundle! = null) {
  7. Get message by "PDUs"
  8. Object[] Objarray = (object[]) bundle.get ("PDUs");
  9. Rebuild SMS
  10. smsmessage[] messages = new Smsmessage[objarray.length];
  11. for (int i=0; i < objarray.length; i++) {
  12. Messages[i] = SMSMESSAGE.CREATEFROMPDU ((byte[]) objarray[i]);
  13. StringBuilder str = new StringBuilder ("From:");
  14. Str.append (Messages[i].getdisplayoriginatingaddress ());
  15. Str.append ("\nmessage:\n");
  16. Str.append (Messages[i].getdisplaymessagebody ());
  17. Toast.maketext (Context, str.tostring (), Toast.length_long)
  18. . Show ();
  19. }
  20. }
  21. }
  22. }
Register receiver

There are two ways of registering:

1. Statically, define receiver in the Androidmanifest.xml application and set the action to be received.

    1. <receiver android:name= ". Smsreceiver ">
    2. <intent-filter>
    3. <action android:name= "Android.provider.Telephony.SMS_RECEIVED"/>
    4. </intent-filter>
    5. </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.
  1. public class Hellodemo extends Activity {
  2. Private Broadcastreceiver receiver;
  3. @Override
  4. protected void OnStart () {
  5. Super.onstart ();
  6. Receiver = new Callreceiver ();
  7. Registerreceiver (receiver, New Intentfilter ("Android.intent.action.PHONE_STATE"));
  8. }
  9. @Override
  10. protected void OnStop () {
  11. Unregisterreceiver (receiver);
  12. Super.onstop ();
  13. }
  14. }
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:

    1. <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:

  1. public class Callreceiver extends Broadcastreceiver {
  2. @Override
  3. public void OnReceive (context context, Intent Intent) {
  4. Telephonymanager Telemanager = (telephonymanager) context.getsystemservice (Context.telephony_service);
  5. Switch (telemanager.getcallstate ()) {
  6. Case telephonymanager.call_state_ringing://Bell
  7. Toast.maketext (Context, "ringing:" + Intent.getstringextra ("Incoming_number"), Toast.length_long). Show ();
  8. Break
  9. Case Telephonymanager.call_state_offhook://Answer
  10. Toast.maketext (Context, "Offhook:" + Intent.getstringextra ("Incoming_number"), Toast.length_long). Show ();
  11. Break
  12. Case Telephonymanager.call_state_idle://Hang off
  13. Toast.maketext (M_context, "Idle:" + Incomingnumber, Toast.length_long). Show ();
  14. Break
  15. }
  16. }
  17. }
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:

  1. public class Callreceiver extends Broadcastreceiver {
  2. Private Context M_context;
  3. @Override
  4. public void OnReceive (context context, Intent Intent) {
  5. M_context = context;
  6. Telephonymanager Telemanager = (telephonymanager) context.getsystemservice (Context.telephony_service);
  7. Telemanager.listen (New Phonestatelistener () {
  8. @Override
  9. public void oncallstatechanged (int state, String incomingnumber) {
  10. Switch (state) {
  11. Case telephonymanager.call_state_ringing://Bell
  12. Toast.maketext (M_context, "ringing:" + incomingnumber, Toast.length_long)
  13. . Show ();
  14. Break
  15. Case Telephonymanager.call_state_offhook://Answer
  16. Toast.maketext (M_context, "Offhook:" + Incomingnumber, Toast.length_long)
  17. . Show ();
  18. Break
  19. Case Telephonymanager.call_state_idle://Hang off
  20. Toast.maketext (M_context, "Idle:" + Incomingnumber, Toast.length_long)
  21. . Show ();
  22. Break
  23. }
  24. }}, Phonestatelistener.listen_call_state);
  25. }
  26. }
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:

    1. <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)

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.