Basic knowledge points of four components of Android interview

What are the four components

content

1.activity

life cycle diagram
write picture description here

1. An Activity is usually an independent window, and the life cycle of Activity in various situations

①The normal life cycle
onCreate –>onStart–>onResume–>onPause–>onStop–>onDestory

②When the horizontal and vertical screens are switched,
if suddenly rotated, the Activity will be destroyed and re-created by default due to the change of the system configuration
write picture description here
. Adding android:configChanges="orientation|keyboardHidden|screenSize"attributes to the Activity can avoid the Activity life cycle being called back .

③The Dialog pops up on the Activity, and when it pops up and then presses the Home button, the life cycle
Activity pops up the Dialog: onCreate–>onStart–>onResume
When starting and exiting the Dialog, the state of the Activity never changes, because the Dialog is actually a View, It belongs to an Activity, so if the Dialog is displayed before the current Activity, it will not affect the life cycle of the Activity.
Press the Home button when the dialog pops up: onPause–>onStop

The whole process is as follows:
write picture description here
④ Switch from the foreground to the background, and then back to the foreground, the Activity life cycle callback method.
write picture description here
⑤The cycle of jumping between the two Activity
MainActivity and DragActivity
write picture description here
MainActivity: onCreate–>onStart–>onResume–>onPause–>onStop–>onRestart–>onStart–>onResume
The cycle experienced by DragActivity: onCreate–>onstart–>onResume –>onPause–>onStop–>onDestory

2. Communication between Activities

 Activity之间通过Intent进行通信
一个 Activity 启动另一个名为 SignInActivity 的 Activity
Intent intent = new Intent(this, SignInActivity.class);
startActivity(intent);

3. Each Activity in the android application should be declared in the AndroidManifest.xml accessory file, otherwise the system will not recognize and execute the Activity

4. The activity is recycled, and the activity state is saved in recovery

Activity provides the onSaveInstanceState() callback method, which is guaranteed to be called before the activity is recycled. The
onSaveInstanceState() method will carry a parameter of type Bundle, which provides some methods for saving data

 @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("data", "保存数据");
    }

The saved data is available in the onCreate() method

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(savedInstanceState!=null){
        String data = savedInstanceState.getString("data");
        }
 }

5. Comparison of four startup modes of Activity

①Standard: The default startup mode of the system. Every time an activity is started, a new instance will be created, regardless of whether the instance exists or not.

②SingleTop: stack top multiplexing mode, if the activity is already on the top of the stack of the task stack, when the same activity is started again, the activity will not be recreated, and its onNewIntent() method will be called,
suitable for receiving notifications to start For example, the news content page of a news client, if you receive 10 news feeds, it is very annoying to open a news content page every time.

③SingleTask: In-stack multiplexing mode, as long as the activity exists in the stack, the instance will not be recreated when the activity is started multiple times. When the instance is started again, the instance will be moved to the top of the stack, and the system will call its onNewIntent() method, which is
suitable for programming The entry point, such as the main interface of the browser, no matter how many applications are started from the browser, the main interface will only be started once, and the rest will go to onNewIntent, and other pages above the main interface will be cleared.

④SingleInstance: The activity of this mode can only be located in a single task stack,
*suitable for pages that need to be separated from the program.
For example : alarm reminder, separate the alarm reminder from the alarm setting*

6. The difference between AlertDialog, popupWindow and Activity

2.service

1. Service life cycle

write picture description here

2. How to start and stop the Service

start the service

Intent startIntent = new Intent(this,MyService.class);
startService(startIntent);

Out of service

Intent stopIntent = new Intent(this,MyService.class);
stopService(stopIntent);

3. How does Activity bind to Service and interact with data

Use Binder objects to connect activities and services
in service

private DownloadBinder downloadBinder = new DownloadBinder();
    class DownloadBinder extends Binder {
        public int getProgress() {
            return 0;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        Log.v(TAG, "onBind: ");
        return downloadBinder;
    }

Create an anonymous inner class of ServiceConnection in Activity and override the onServiceConnected() and onServiceDisconnected() methods

private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
        //在Activity中调用Binder中的方法
            MyService.DownloadBinder binder = (MyService.DownloadBinder) service;
            int progress = binder.getProgress();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

bind service

Intent startIntent = new Intent(this,MyService.class);
bindService(startIntent,connection,BIND_AUTO_CREATE);
//BIND_AUTO_CREATE 在活动和服务绑定后自动创建服务

Unbind service

unbindService(connection);

4. How to start the corresponding Service in Activity

Three.broadcast

1. Please describe your understanding of broadcasting BroadcastReceiver

①It is one of the four major components, mainly used to accept the broadcast sent by the APP ②Internal
communication implementation mechanism: through the Binder mechanism of the android system ③Broadcast is
mainly divided into two types

  • Standard broadcast: It is a completely asynchronous broadcast. After the broadcast is sent, all broadcast receivers will receive the broadcast message at the same time at almost the same time. This broadcast is more efficient, but it also means that it cannot be used. truncated
  • Ordered broadcast: It is a broadcast that is executed synchronously. After the broadcast is sent, only one broadcast receiver can receive the broadcast message at the same time. When the logic in the broadcast receiver is executed, the broadcast will continue to be delivered. All broadcast receivers at this time are in sequence, and those with higher priority are broadcasted first, and the previous broadcast receiver can also truncate the broadcast being delivered, so that the latter broadcast receiver cannot receive the broadcast message.

2. Classification of broadcasting, what is the difference between local broadcasting and global broadcasting

  • Global broadcast: that is, the broadcast can be received by any other application, and can also receive broadcasts from any other application. This can easily lead to security issues
  • Local broadcast: The broadcast issued by the local broadcast mechanism can only be delivered within the application, and the broadcast receiver can only receive broadcasts from the application

3. Ways and scenarios of broadcast use

  • Create a broadcast receiver, create a new class to inherit BroadCast, and override the onReceive() method.
  • Usage scenarios:
    1.App global monitoring, this kind of broadcast receiver is mainly used for static registration in AndroidManifest. Generally, after receiving the message, we need to do some corresponding actions, and these actions are related to the components of the current App, such as Whether the Activity or Service is running is irrelevant. For example, when we integrate a third-party Push SDK, we generally add a statically registered BroadcastReceiver to monitor Push messages. When a Push message comes, it will make some network requests or send notifications in the background, etc. .
    2. Partial monitoring of components, this is mainly a broadcast receiver dynamically registered using registerReceiver() in Activity or Service, because when we receive some specific messages, such as when the network connection changes, we may need to display the current Activity page Give the user some UI prompts, or suspend the network request task in the Service. So this kind of dynamically registered broadcast receiver is suitable for specific message processing of specific components

4. How to register and use BroadcastReceiver in manifest and code

  • Dynamic registration: Registering in the code, dynamic broadcasting is best to register in onResume() of Activity, deregister in onPause(), register in onResume(), deregister in onPause() because onPause() will be executed before the App dies, thus Ensure that the broadcast will be logged out before the App dies to prevent memory leaks
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.intent.action.ACTION_SHUTDOWN");
registerReceiver(new CommonBroadcastReceiver(),intentFilter);
  • Static registration: register in AndroidManifest.xml
<receiver android:name=".broadcast.CommonBroadcastReceiver">
            <intent-filter>
                <!-- 关机广播 -->
                <action android:name="android.intent.action.ACTION_SHUTDOWN" />
            </intent-filter>
</receiver>

Four. contentProvider

1. Talk about your understanding of ContentProvider

ContentProvider manages the data that android stores in a structured way. It encapsulates data in a relatively secure way and provides easy handling mechanisms. Content providers provide standardized interfaces for data interaction between different processes. Ensure the security of the accessed data. Content providers can choose only which part of the data to share, so as to ensure that there is no risk of leakage of private data in our program.

2. Talk about the relationship between ContentProvider, ContentResolver, and ContentObserver

ContentResolver provides a series of methods for CRUD data, the content URI establishes a unique identifier for the data in the content provider ContentProvider, and ContentObserver monitors changes in Uri data

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325650618&siteId=291194637