Explain the four application components of Android in detail

Time:2022-7-28

A core feature of Android is that an application can be used as an element in other applications to provide data for other applications. For example, if a program needs to use some controls to load some pictures, and another program has developed this function and can be used by other programs, you can directly use the cross process communication to call the function of that program, rather than developing another one yourself. In order to achieve such a function, the Android system must be able to start its process when any part of the application is needed, and instantiate that part of the Java object. Therefore, unlike programs in most other systems, Android programs do not have a single entry point, but they have components necessary for system instantiation and operation. Android provides four components; In addition to the broadcastreceiver, the four components in Android, activity, service and ContentProvider must be registered in androidmanifest.xml, while broadcastreceiver can be registered in androidmanifest XML file, or Java code or kotlin code; After Android 8.0, on androidmanifest The failure of static registration broadcast reception in the XML file is due to the official optimization of power consumption, which is a processing method to avoid app abuse of broadcast.

1、Activity

Activity is a display component, which provides a visual user interface for users. For example, a calling program may have an activity to display contacts that can make calls, a second activity to create new contacts and write information, and other activities to view specific contacts or change contact information. Although the user interface provided by each activity in the application is highly aggregated, each activity is independent of other activities, Every instantiated activity is a subclass of activity. Intent can trigger the start of activity. Intent can be divided into explicit intent trigger and implicit intent trigger; Explicit intent trigger can clearly point to activity components, which is represented by the following code:


 Intent in = new Intent(this,SecondActivity.class)
 MainActivity.this.startActivity(in)

Implicit intent trigger refers to the target component that points to one or more activities. It can also have no target activity. Its implicit trigger is represented by the following code:


Intent intent = new Intent();
intent.setPackage("com.xe.launchmode");
intent.setAction("com.xe.actoin.MAP");
intent.addCategory("android.intent.category.APP_MAPS");
MainActivity.this.startActivity(intent);

2、Service

Service is a background processing task-based component, which is always running in the background. It is used to play background music when processing a series of computing tasks or other things in the background. Each service is extended from the service class; The startup of service component and activity component is different. Activity has only one startup state, which is represented by the following code:


Intent in = new Intent(this,SecondActivity.class)
startActivity(in)

There are two ways to start a service. When it is started, it can do some background tasks without interacting with the user interface. Its life cycle is as long as that of an application. Playing music by a multimedia player is a very good example of an application service. The multimedia player program may contain one or more activities through which users can select and play music. However, music playback does not need an activity to process, because users may want the music to play forever, even if they quit the player to execute other applications. In order to keep music playing, the multimedia player activity may start a service to play music in the background. The Android system will keep the music playback service running even after the activity that started the service exits. Its startup can be represented by the following code:


Intent in = new Intent(this,SecondActivity.class)
MainActivity.this.startService(in)

When it is in the binding state, it can do some background tasks and interact with the user interface. Its life cycle is as long as the user interface. Its binding can be represented by the following code:


ServiceConnection mBinderPoolConnection = new ServiceConnection() {
  @Override
  public void onServiceConnected(ComponentName name, IBinder service) {
   
  }

  @Override
  public void onServiceDisconnected(ComponentName name) {

  }
 };
 
Intent intent = new Intent(mContext, MyService.class); 
MainActivity.this.bindService(intent,new ServiceConnection(),Context.BIND_AUTO_CREATE);

No matter which one is enabled in the above 2, you can’t directly do time-consuming operations in the service, because it runs in the main thread. If you have to do time-consuming operations, you should open a working thread for it to execute.

3、BroadcastReceiver

Generally, it does not perform any tasks, but only receives and broadcasts notifications accordingly. Most broadcast notifications are generated by the system, such as changing the time zone, alarm clock reminder, user selecting a picture or user changing the language preference. Applications can also send broadcast notifications, such as notifying other applications that some data has been downloaded to the device and can be used; The broadcastreceiver of an application responds to its notification. All the implementation classes of broadcastreceiver are extended from the broadcastreceiver class. Broadcastreceiver is suitable for communication between different components and processes. It has no user interface because it works inside the system. The following two registration methods are introduced. The first is static registration, which is in androidmanifest It is completed in the XML file, which will be parsed by the application when installing the application, and can receive the broadcast without starting the application, which is represented by the following code to monitor the change of WiFi status:


<receiver android:name=".myapplication.receiver.WifiReceiver">
 <intent-filter>
   <action android:name="android.net.wifi.RSSI_CHANGED" />
   <action android:name="android.net.wifi.STATE_CHANGE" />
   <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
  </intent-filter>
</receiver>

From the above code, we can find that the matching of the reception process is described by <intent-filter>, and we can conclude that broadcasting is a low coupling observer mode.
Another way is dynamic registration. You need to start the application to receive the broadcast. The registration is completed in Java code, and its dynamic registration is represented by the following code:


public class MyBroadcastReceiver extends BroadcastReceiver{
  @Override
  public void onReceive(Context context, Intent intent){
   
  }
 }
 
 
 MyBroadcastReceiver receiver = new MyBroadcastReceiver();
 IntentFilter filter=new IntentFilter();
 filter.addAction("com.xe.intent.action.ACTION_1");
 filter.addAction("com.xe.intent.action.ACTION_2");
 SecondActivity.this.registerReceiver(receiver,filter);

Sending broadcast can be realized by the following code:


Intent intent = new Intent();
intent.setAction("com.xe.intent.action.ACTION_2");
MainActivity.this.sendBroadcast(intent);

In the above two broadcast registration methods, the broadcast receiving method cannot be time-consuming, because the broadcast receiving method is called in the main thread.

4、ContentProvider

ContentProvider is a shared data component. Applications can access the data of other applications through ContentProvider, including the private data of other applications; Like service, it has no user interface. It needs to implement insert, update, delete and query methods internally. It uses a data set internally and has no requirements for data sets. ContentProvider communicates across processes. When the Android system receives a request that requires a component to process, Android will ensure that the host process of the component that processes the request is already running. If not, start the process immediately. ContentProvider provides an external interface contentresolver to access data for other processes. The following part of the code simply represents the use process of the query method:


Uri bookUri = Uri.parse("content://com.zyb.provider/data");
ContentResolver cr = ContentProviderActivity.this.getContentResolver();
Cursor bookCursor = cr.query(bookUri,new String[]{"_id","name"},null,null,null);
while (bookCursor.moveToNext()) {
 int id = bookCursor.getInt(0);
 String name = bookCursor.getString(1);
}

In the above code, first create the URI to access the data, then obtain the contentresolver interface through the application, obtain the cursor object of the data collection through this interface, and finally obtain the final required data through the cursor object lookup index. Well, the content of this chapter is written here. Due to my limited technology, the article will inevitably make mistakes, and I hope to be criticized and corrected; Later, I will write the source code analysis of the working process of the four Android components sometime. Thank you for reading.

The above is the detailed content of Android application components. For more information about Android application components, please pay attention to other relevant articles of developeppaer!