Original link: https://github.com/GeniusVJR/LearningNotes/blob/master/Part1/Android/Android基础知识.md
-
FrameLayout
This layout is the simplest among the five layouts. Android does not control the arrangement of child views, and all controls in this layout will default to appear in the top left corner of the view. We can use
android:layout_margin
,android:layout_gravity
and other attributes to control the position of child controls relative to the layout. -
LinearLayout
A linear layout that controls only one control per row, so when many controls need to be listed on a single screen, LinearLayout can be used. This layout has a property that needs special attention:
android:orientation="horizontal|vertical
. -
When
android:orientation="horizontal
, it indicates that you want to hand over the horizontal layout to LinearLayout , and its child elements’android:layout_gravity="right|left"
and other horizontal gravity values are ignored. At this point, the child elements in LinearLayout are arranged from left to right by default. We can useandroid:layout_gravity="top|bottom"
and other gravity values to control vertical display. -
Conversely, it can be understood that when
android:orientation="vertical
, LinearLayout will handle the display of its child elements accordingly. -
AbsoluteLayout
Can place multiple controls and define the x,y position of the controls.
-
RelativeLayout
This layout is also relatively free, Android analyzes the horizontal layout & vertical layout of the child views in this layout. Thus, we can use tags or Java code to control the views in the vertical and horizontal directions based on FrameLayout.
android:layout_centerInParent="true|false" android:layout_centerHorizontal="true|false" android:layout_alignParentRight="true|false"
-
Related attributes:
-
TableLayout
Distributes child elements to rows or columns, a TableLayout consists of many TableRows.
Activity lifecycle.
-
Starting Activity: onCreate()—>onStart()—>onResume(), Activity enters the running state.
-
Activity goes to the background: Current Activity transitions to a new Activity interface or presses the Home key to return to the main screen: onPause()—>onStop(), enters the stagnant state.
-
Activity returns to the foreground: onRestart()—>onStart()—>onResume(), returns to the running state again.
-
Activity goes to the background and the system memory is insufficient, the system will kill this background Activity (at this time, this Activity reference is still in the task stack, but the object it points to is null). If you return to this Activity again, it will go through onCreate()–>onStart()—>onResume() (the Activity initialization lifecycle will run again).
-
Locking and unlocking the screen will only call onPause() and will not call onStop(). After unlocking, onResume() will be called.
-
For more process branches, please refer to the following lifecycle flowchart.
-
Change the default behavior of the task stack through the Activity’s XML tag.
-
Use
android:launchMode= "standard|singleInstance| singleTask|singleTop"
to control the Activity task stack.The task stack is a last-in-first-out structure. The Activity at the top of the stack is in focus, and when the back button is pressed, the Activities in the stack will exit one by one, calling their
onDestroy()
method. If there are no Activities in the stack, the system will recycle this stack; each app has only one stack by default, named after the app’s package name. -
standard : Standard mode, every time an Activity is started, a new Activity instance will be created and pushed to the top of the task stack, regardless of whether this Activity already exists. The three callbacks for Activity startup (onCreate()->onStart()->onResume()) will all be executed.
-
singleTop : Stack top reuse mode. In this mode, if the new Activity is already at the top of the task stack, this Activity will not be recreated, so its three startup callbacks will not be executed. Instead, the Activity’s
onNewIntent()
method will be called. If the Activity already exists but is not at the top of the stack, it will behave like standard mode. -
singleTask: Stack reuse mode. When creating this kind of Activity, the system will first confirm if its required task stack has been created; if not, it will create the task stack first. Then it will put the Activity in. If there is already an Activity instance in the stack, this Activity will be brought to the top of the stack,
onNewIntent()
, and singleTask will clear all Activities above the current Activity (clear top). -
singleInstance : Enhanced version of singleTask mode. An Activity in this mode can only be located alone in one task stack. Due to the characteristic of stack reuse, no new Activity will be created for subsequent requests unless this unique task stack is destroyed by the system.
The management of Activity’s stack is based on ActivityRecord, and all ActivityRecords are placed in a List. You can think of an ActivityRecord as an Activity stack.
Activity caching methods.
There are two Activities a and b. After entering b from a for a while, the system may recycle a. When back is pressed, it does not execute a’s onRestart but rather the onCreate method, causing a to be recreated, which may result in the loss of temporary data and state in a.
You can use the onSaveInstanceState() callback method in Activity to save temporary data and state. This method will definitely be called before the activity is recycled. The method has a Bundle parameter, where putString(), putInt(), etc., need to pass two parameters, a key and a value. After the data is saved, it will be restored in onCreate, which also has a Bundle type parameter.
Example code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Here, when the Activity is first created, it is empty
// So we need to check
if( savedInstanceState != null ){
savedInstanceState.getString("anAnt");
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("anAnt","Android");
}
1. onSaveInstanceState (Bundle outState)
When an activity becomes “easy” to be destroyed by the system, its onSaveInstanceState will be executed, unless the activity is actively destroyed by the user, such as when the user presses the BACK key.
Note the double quotes above, what does “easy” mean? It implies that the activity has not been destroyed yet, but there is only a possibility of it being destroyed. What are these possibilities? By overriding all lifecycle onXXX methods of an activity, including onSaveInstanceState and onRestoreInstanceState methods, we can clearly know when a certain activity (let’s assume activity A) is displayed at the top of the current task, its onSaveInstanceState method will be executed in several situations:
1. When the user presses the HOME key.
This is obvious; the system does not know how many other programs you want to run after pressing HOME, and naturally does not know whether activity A will be destroyed. Therefore, the system will call onSaveInstanceState, allowing the user the opportunity to save some non-permanent data. The following analyses of situations all follow this principle.
2. Long press the HOME key and select to run other programs.
3. Press the power button (turn off the screen display).
4. Start a new activity from activity A.
5. Switch the screen orientation, such as from portrait to landscape (if the config change attribute is not specified). Before the screen switch, the system will destroy activity A, and after the screen switch, the system will automatically recreate activity A, so onSaveInstanceState will definitely be executed.
In summary, the invocation of onSaveInstanceState follows an important principle: when the system destroys your activity “without your permission”, onSaveInstanceState will be called by the system. It is the system’s responsibility because it must provide an opportunity for you to save your data (of course, if you do not save, it is up to you).
Additionally, several points to note:
1. Every View in the layout implements the onSaveInstanceState() method by default, so any changes to this UI will be automatically stored and restored when the activity is recreated. However, this only works if you provide a unique ID for this UI; if you do not provide an ID, its state will not be stored.
2. Since the default implementation of onSaveInstanceState() helps the UI store its state, if you need to override this method to store additional state information, you should call the parent class’s onSaveInstanceState() method (super.onSaveInstanceState()) before executing any code. Since there is already a ready-to-use method, do we still need to implement onSaveInstanceState()? It depends on the situation. If you have variables in your derived class that affect the UI or the behavior of your program, you certainly need to save that variable, which requires implementation; otherwise, it is not necessary.
3. Due to the uncertainty of when onSaveInstanceState() is called, you should only use this method to record the transient state of the activity (UI state). You should not use this method to store persistent data. When the user leaves this activity, persistent data should be stored in the onPause() method (for example, data that should be stored in a database).
4. If onSaveInstanceState() is called, this method will be triggered before onStop(), but the system does not guarantee whether it will be triggered before or after onPause().
2. onRestoreInstanceState (Bundle outState)
As for the onRestoreInstanceState method, it should be noted that the onSaveInstanceState method and the onRestoreInstanceState method are not necessarily called in pairs (I found out last night during debugging that they are not necessarily called in pairs!).
onRestoreInstanceState is called under the premise that activity A is “indeed” destroyed by the system. If it is merely in a situation where it might be destroyed, then this method will not be called. For example, when activity A is displayed, the user presses the HOME key to return to the main screen, and then immediately returns to activity A. In this case, activity A generally will not be destroyed by the system due to memory reasons, and thus the onRestoreInstanceState method of activity A will not be executed.
Additionally, the bundle parameter of onRestoreInstanceState will also be passed to the onCreate method, and you can choose to restore data in the onCreate method. Moreover, onRestoreInstanceState executes after onStart. As for the use of these two functions, here is a sample code (note the custom code’s position relative to the super call):
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean("MyBoolean", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "Welcome back to Android");
// etc.
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}
Fragment’s lifecycle and its relationship with Activity
Here we refer to an image from this knowledge base:
Why create child threads in Service rather than in Activity
This is because it is difficult for Activity to control Threads. Once the Activity is destroyed, there is no way to retrieve the previously created child thread instance. Moreover, a child thread created within an Activity cannot be operated on by another Activity. However, Service is different; all Activities can associate with Service and easily operate its methods. Even if the Activity is destroyed, as long as it re-establishes the association with the Service, it can retrieve the original Binder instance within the Service. Therefore, using Service to handle background tasks allows Activity to finish without worrying about controlling background tasks.
How to use Intent and what data types can be passed.
By querying the Intent/Bundle API documentation, we can learn that Intent/Bundle supports passing basic data types and arrays of basic types, as well as String/CharSequence types and their arrays. For other types of data, it seems powerless. However, we can see in the Intent/Bundle API that Intent/Bundle can also pass Parcelable and Serializable types of data, as well as their arrays/lists.
Therefore, to transmit non-basic types and non-String/CharSequence types of data via Intent/Bundle, we need to implement the Parcelable interface or the Serializable interface in the data types.
http://blog.csdn.net/kkk0526/article/details/7214247
Fragment Lifecycle
Note the differences compared to Activity, in execution order:
-
onAttach(), onDetach()
-
onCreateView(), onDestroyView()
Two methods to start a Service, what are the differences?
1. In Context, use public boolean bindService(Intent service, ServiceConnection conn, int flags)
to associate and start the Service, and the Service’s lifecycle is dependent on the Context.
2. Use public ComponentName startService(Intent service)
to start a Service, at this point, the Service’s lifecycle is independent of the Context that started it.
3. Note that whatever, you need to register your Service in the xml, like this:
<service
android:name=".packnameName.youServiceName"
android:enabled="true" />
The difference between two types of Broadcast Receiver registration: dynamic and static.
-
Static registration: Registered in the AndroidManifest.xml file. When the App exits, the Receiver can still receive broadcasts and handle them.
-
Dynamic registration: Registered dynamically in the code. When the App exits, it can no longer receive broadcasts.
How to use ContentProvider
http://blog.csdn.net/juetion/article/details/17481039
Can we ensure that the service will not be killed?
Set the Service to START_STICKY.
-
After being killed, it will be restarted (after about 5 seconds), and the Intent will be resent, maintaining the same state as before being restarted.
Increase the priority of the service.
-
In the AndroidManifest.xml file, you can set the highest priority for the intent-filter using
android:priority = "1000"
. 1000 is the highest value; if the number is smaller, the priority is lower. This also applies to broadcasts. -
[Conclusion] Currently, it seems that this priority attribute only applies to broadcasts and may not be effective for Services.
Increase the priority of the service process.
-
Processes in Android are managed. When the system’s process space is tight, it will automatically recycle processes based on priority.
-
When a service runs in a low-memory environment, some existing processes will be killed. Therefore, the priority of the process will be very important. You can use startForeground() to place the service in the foreground state. This will reduce the chances of being killed in low memory situations.
-
[Conclusion] If the service is still killed under extremely low memory pressure, it will not necessarily restart.
Restart the service in the onDestroy method.
-
Service + broadcast method: When the service executes onDestroy(), send a custom broadcast. When the broadcast is received, restart the service.
-
You can also directly call startService in onDestroy().
-
[Conclusion] When using third-party applications like task killers or in settings – applications – force stop, the app process may be killed directly, and the onDestroy method may not even be entered, so it cannot be guaranteed.
Listen for system broadcasts to determine the Service status.
-
Listen and capture system broadcasts such as: phone reboot, interface wake-up, application status changes, etc., and then determine whether our Service is still alive. Don’t forget to add permissions.
-
[Conclusion] This can also be considered a measure, but it feels like too much listening can lead to confusion with the Service, causing many inconveniences.
In the JNI layer, use C code to fork a process.
-
This process will be considered two different processes by the system. However, this may not work after Android 5.0.
After rooting, place it in system/app to become a system-level application.
Big move: Place a pixel in the foreground (like QQ).
What are the two types of animations, and what are their characteristics? What are the differences between the three types of animations?
-
Tween animation. By specifying the initial and final states of the View and the duration and method of change, a series of graphic transformations are completed to achieve animation effects. Alpha, Scale, Translate, Rotate.
-
Frame animation AnimationDrawable controls animation-list xml layout.
-
Property Animation.
Data storage methods in Android.
-
SQLite: SQLite is a lightweight database that supports basic SQL syntax and is a commonly used data storage method. Android provides a class named SQLiteDatabase for this database, encapsulating some APIs for database operations.
-
SharedPreference: Another common data storage method besides SQLite, which is essentially an xml file, commonly used to store simpler parameter settings.
-
File: Commonly referred to as file (I/O) storage method, often used to store large amounts of data, but the downside is that updating data can be difficult.
-
ContentProvider: A data storage method in the Android system that allows all applications to share data. Since data is usually private among applications, this storage method is used less frequently, but it is still an essential storage method. For example, audio, video, images, and contacts can generally be stored using this method. Each Content Provider will provide a public URI, and when an application needs to share data, it will define a URI for that data using the Content Provider, and other applications will access the data through that URI.
Basic operations of SQLite.
http://blog.csdn.net/zgljl2012/article/details/44769043
How to determine if an application has been force killed.
Define a static constant in the Application, set it to -1, change it to 0 on the welcome screen. If it is force killed, the application will reinitialize, and the parent Activity will check the value of that constant.
How to solve the issue of being force killed.
Checking if it has been force killed in the onCreate of each Activity is redundant. Encapsulate it in the parent class of Activity. If it has been force killed, jump back to the main screen. If it has not been force killed, perform the Activity initialization operation, pass intent parameters to the main screen, and the main screen will call onNewIntent. In onNewIntent, jump back to the welcome screen to re-run the process.
What are the advantages and disadvantages of JSON?
How to exit and terminate the App.
The difference between the Asset directory and the res directory.
How to speed up Activity startup in Android.
Memory optimization methods in Android: ListView optimization, timely resource closure, image caching, etc.
Application scenarios of weak references and soft references in Android.
The four attributes of Bitmap and the size of each attribute.
Classification of View and View Group. The process of customizing View: onMeasure(), onLayout(), onDraw().
How to customize controls:
-
Declaration and acquisition of custom attributes.
-
Analyze the required custom attributes.
-
Declare in res/values/attrs.xml.
-
Use in layout file.
-
Obtain in the View’s constructor.
Measurement onMeasure.
Layout onLayout(ViewGroup).
Drawing onDraw.
onTouchEvent.
onInterceptTouchEvent(ViewGroup).
State restoration and saving.
How to handle heartbeat mechanisms in Android long connections.
View tree drawing process.
Pull-to-refresh implementation principles.
What frameworks have you used, have you seen the source code, do you know the underlying principles?
Retrofit.
EventBus.
Glide.
New features in Android 5.0 and 6.0.
New features in Android 5.0:
-
Material Design style.
-
Support for multiple devices.
-
Support for 64-bit ART virtual machine.
New features in Android 6.0:
-
A large number of beautiful and smooth animations.
-
Support for quick charging switches.
-
Support for dragging applications into folders.
-
New professional mode in the camera.
New features in Android 7.0:
-
Split-screen multitasking.
-
Enhanced Java 8 language mode.
-
Night mode.
The difference between Context.
-
Activity, Service, and Application Context are different. Activity inherits from ContextThemeWrapper, while others inherit from ContextWrapper.
-
Each Activity, Service, and Application Context is a new ContextImpl object.
-
getApplication() is used to obtain the Application instance, but this method can only be called in Activity and Service. In most cases, we use Application in Activity or Service, but if we want to obtain the Application instance in other scenarios, such as BroadcastReceiver, we can use getApplicationContext(). This method has a broader scope; any instance of Context can call getApplicationContext() to obtain the Application object.
-
When an Activity is created, it creates a ContextImpl object and associates it in the attach method. Application and Service are similar. The methods of ContextWrapper internally delegate to the methods of ContextImpl.
-
It is not allowed to create a dialog using the Application’s Context.
-
Although Application, Activity, and Service each have their ContextImpl, and each ContextImpl has its mResources member, since their mResources members come from a unique ResourcesManager instance, they all point to the same memory.
-
The number of Contexts equals the number of Activities + the number of Services + 1, where 1 is for Application.
Usage scenarios and characteristics of IntentService.
IntentService is a subclass of Service, an asynchronous service that stops automatically, effectively solving the problem of forgetting to stop and destroy the Service after completing time-consuming operations in traditional Services.
Advantages:
-
On one hand, there is no need to create a new Thread.
-
On the other hand, there is no need to consider when to close the Service.
In onStartCommand, onStart is called, during which messages are sent to the handler’s handleMessage. Finally, handleMessage calls onHandleIntent(intent).
Image caching.
Check the maximum available memory for each application:
int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
Log.d("TAG", "Max memory is " + maxMemory + "KB");
Gradle.
Build tools, Groovy syntax, Java.
The jar file only contains code, while the aar file contains not only code but also…
How did you self-learn Android?
First, read books and watch videos while coding, then read blogs from experts, work on projects, submit code to GitHub, and when I feel comfortable with the API, I start reading advanced books and the source code, learning some ideas from the source code, start creating my own wheels, and think about code improvement, such as design patterns, architecture, refactoring, etc.
About Java and Android Expert Channel
Java and Android Expert Channel is a public account with tens of thousands of followers discussing Java and Android development, sharing and creating the most valuable articles to help you become an expert in this field!
We discuss the cutting-edge technologies in Android and Java development: Android performance optimization, pluginization, cross-platform, dynamic, strengthening and anti-cracking, etc., as well as design patterns/software architecture. We are a team composed of engineers from BAT.
Follow us for a red packet, reply: “Baidu”, “Ali”, “Tencent” for surprises!!! After following, you can join the WeChat group. The group consists of experts from Baidu, Ali, and Tencent.
Welcome to follow us, let’s discuss technology together. Scan and long-press the QR code below to quickly follow us. Or search for the public account: JANiubility.
Public account: JANiubility