Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Select the interview questions of large foreign factories, can you give the correct answer?

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > IT Information >

Share

Shulou(Shulou.com)11/24 Report--

This article comes from the official account of Wechat: ByteCode (ID:ByteCode1024), author: programmer DHL

Accustomed to open medium every day to take a look at technology-related content, happened to see a boss to share and Android Lifecycle-related interview questions, think it is very valuable.

Android Lifecycle is a very important knowledge point in Android development. Unfortunately, I find that many new Android developers don't know much about Android Lifecycle, which leads to a lot of strange problems in their development.

Sharing these interview questions is not only to pass the interview, but also to give Android developers a more solid foundation and prevent a lot of strange problems in development.

Interview question 1: Launch Fragment by Default question:

Take a few seconds to think about what's wrong with the following code.

Class MainActivity: AppCompatActivity () {override fun onCreate (savedInstanceState: Bundle?) {super.onCreate (savedInstanceState) setContentView (R.layout.activity_main) supportFragmentManager .beginTransaction () .replace (R.id.container, MainFragment ()) .commit ()} wrong answer

Did not use KTX to add Fragment

Should use .add instead of .replace

The correct answer

If the Activity is accidentally killed and restored, the onCreate () method is executed again to create a new Fragment, so there will be two Fragment in the stack. Any operation on Fragment can be performed twice, which can lead to strange problems.

In order to prevent the recovery of Activity from being killed accidentally, resulting in the addition of a new Fragment, we can use stateInstanceState = = null as a judgment condition to prevent the addition of a new Fragment, so we can simply modify the above code.

Class MainActivity: AppCompatActivity () {override fun onCreate (savedInstanceState: Bundle?) {super.onCreate (savedInstanceState) setContentView (R.layout.activity_main) if (savedInstanceState = = null) {supportFragmentManager .beginTransaction () .replace (R.id.container MainFragment () .commit ()}} interview question 2: Create Fragment with Constructor question:

If you add parameters to the Fragment constructor and take a few seconds to think about it, what's wrong with the following code?

SupportFragmentManager .beginTransaction () .replace (R.id.container, MainFragment ()) .commit () class MainFragment (privateval repository: Repository): Fragment () {} wrong answer

We can use the .replace (R.id.container, MainFragment (repository)) method instead

It will not compile and run

The correct answer

We should not instantiate any Fragment () directly with a constructor with arguments. If you want to instantiate Fragment () with a constructor with arguments, you can use FragmentFactory to solve this problem, which is a new addition of API in AndriodX Fragment 1.2.0. For details, see another article, Google recommends the use of these new features of Fragment.

If you do not use the AndriodX Fragment library, the system does not support it by default. Although the above code can be compiled and run normally, it will crash during the destruction and recovery process because of configuration changes. The error message is shown below.

Caused by: java.lang.NoSuchMethodException: MainFragment. This is because the system needs to reinitialize it in some cases, such as configuration changes, such as when the device is rotated, causing the Fragment to be destroyed. If there is no default empty constructor, the system does not know how to reinitialize the Fragment instance.

Therefore, we always need to make sure that there is an empty constructor when instantiating Fragment.

Interview question 3: Instantiate ViewModel DirectlyViewModel is a member of the Jetpack architecture component. Take a few seconds to think about what's wrong with the following code.

Class MainActivity: AppCompatActivity () {privateval viewModel = MainViewModel ()} class MainViewModel (): ViewModel {} wrong answer

There is no problem, it can compile and run normally.

We also need to inject some dependencies into it, such as MainViewModel (repository)

Correct answer

We should not instantiate ViewModel directly. ViewModel is a member of the Jetpack schema component, which means that it can survive configuration changes, such as when the device rotates, it has a longer life cycle than Activity.

If we instantiate ViewModel directly in the code, although it works, it will become a normal ViewModel, losing its original features.

Therefore, to instantiate ViewModel, it is recommended that you use ViewModel KTX, as shown below.

Class MainActivity: AppCompatActivity () {privateval viewMode:MainViewModel by viewModels ()} by viewModels () instantiates a new ViewModel when it restarts or recovers from a killed process. If there is a configuration change, such as when the device is rotated, it checks to see if the ViewModel has been created without recreating it

ViewModels () will automatically inject SavedInstancestate (such as SavedInstanceState and Intent in Activity) as needed, and if we have other dependencies injected through Dagger Hilt, it will use the following parameters with ViewModel

@ HiltViewModelclass MyViewModel @ Inject constructor (privateval repository: Repository, savedStateHandle: SavedStateHandle): ViewModel {} interview question 4: ViewModel as StateRestoration Solution question:

What is the purpose of the ViewModel provided by the Jetpack architecture components?

Class MainActivity: AppCompatActivity () {privateval viewMode:MainViewModel by viewModels () / / Some other Activity Code} wrong answer

ViewModel is used for state recovery, for example, when Activity is killed and restarted, ViewModel is used to help restore to the original state.

Correct answer

ViewModel is actually one of the Jetpack architecture components provided by google, which encourages Android developers to use the MVVM design pattern.

It also has other important functions, such as when the device rotates, even if the Activity and Fragment are destroyed, their respective ViewModel is retained, and Google provides a parameter called savedStateHandle in ViewModel, which is used to save and recover data.

Interview question 5: LiveData as State Restoration Solution question:

What is the purpose of the LiveData provided by the Jetpack architecture components.

/ / Declaring itval liveDataA = MutableLiveData () / / Trigger the value changeliveDataA.value = someValue wrong answer:

It exists to ensure that the data survives the life cycle of the Activity. When Activity returns from the process destruction, the data will be automatically recovered.

Correct answer

LiveData itself cannot survive process destruction. It is a special type of data that controls the value emitted by the observer (Activity or Fragment) according to its life cycle.

The ViewModel still exists after the configuration changes, so so is the LiveData within the ViewModel. This ensures that the LiveData emission values are controlled as shown in the following figure.

However, LiveData itself cannot survive process destruction. When memory runs out, Activity is killed by the system and ViewModel itself is destroyed.

To solve this problem, Google provides a parameter called savedStateHandle in ViewModel, which is used to save and recover data so that it persists after the process is destroyed.

@ HiltViewModelclass MyViewModel @ Inject constructor (privateval repository: Repository, savedStateHandle: SavedStateHandle): ViewModel {/ / Some other ViewModel Code} this is an enhanced mechanism for handling Intent and SavedInstanceState, which were previously handled separately by Activity.

To ensure that the Livedata is saved, we can check in SavedStateHandle to see if the Livedata has been created.

Val liveData = savedStateHandle.getLiveData (KEY) similarly, this applies to stateFlow, which can survive process destruction.

Val stateFlow = savedStateHandle.getStateFlow (KEY, 0) so LiveData itself is not used to recover data.

Interview question 6: When is The View Destroyed But Not the Instance question:

There is usually a view in Activity or Fragment. You can provide me with a scenario where the view of the instance is corrupted, but the instance (such as Activity or Fragment) still exists.

Wrong answer

When the configuration changes (for example, device rotation)

When memory runs out, App runs in the background, and the process kills App

Correct answer

In fact, Activity is always destroyed along with its view. Therefore, there is no onDestroyView () lifecycle method in Activity.

The onDestroyView () lifecycle method is available only in Fragment. In most cases, the Fragment is destroyed along with its view.

But when you replace one Fragment with another Fragment through Fragment transaction, the Fragment under the stack still exists, but its view is corrupted.

When a Fragment is replaced by another Fragment, the onDestroyView () method is called, but the onDestroy () or onDetect () methods are not called.

Because of this complexity, there are a lot of strange problems when using Fragment. Questions related to Fragment will be shared in later articles.

Question 7: Lifecycle Aware Coroutine uses collaborators in App, how to ensure that their lifecycles are perceptible.

Wrong answer

For normal views, just use lifecycleScope in Activity or Fragment and viewModelScope in ViewModel

For composite views, you need to use the collectAsState () method in stateFlow, because when the composable function is inactive, it does not collect the

Correct answer

For normal views, even if lifecycleScope is available, it is active throughout the lifecycle of Activity or Fragment. Because sometimes we want certain scenarios to be active only after onStart () or onResume ().

To do this, we need to use an API like repeatOnLifecycle in lifecycleScope to provide additional scope.

LifecycleScope.launch {repeatOnLifecycle (Lifecycle.State.STARTED) {viewModel.stateFlowValue.collect {/ / Do something}} their variants are shown in the following figure.

For the composite view collectAsState (), it does not guarantee the safe use of data while the composite function is active, nor does it stop sending StateFlow, which leads to a waste of resources.

To ensure that only when Activity or Fragment is in the correct life cycle, such as after onStart (), we need to use collectAsStateWithLifecycle () and WhileSubscribed (...) in stateFlow.

When we study the collectAsStateWithLifecycle () source code, we find that it also uses repeatOnLifecycle (...) .

This is the end of the full text. Thank you for reading.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

IT Information

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report