Let's talk about Android Jetpack

Based on the components of the Android architecture, Kotlin coroutine + retrofit is integrated to simulate the network for rapid development in an all-round way.

Navigation

NavController manages the objects of application navigation in NavHost, navigates to a specific target along a specific path in the navigation map, or directly navigates to a specific target.

First, define layout / activity_main.xml

 <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />

Second, define navigation / mobile_navigation.xml

To add Activity, you need to first create the corresponding Activity in Project, which can be processed in the layout designer.

<navigation  
<fragment
     android:id="@+id/navigation_home"
     android:name="com.android.myapplication.ui.home.HomeFragment"
     android:label="@string/title_home"
     tools:layout="@layout/fragment_home">

        <action
         android:id="@+id/action_navigation_home_to_detail_activity"
         app:destination="@id/detail_activity" />
 </fragment>
   ...
 <activity
     android:id="@+id/detail_activity"
     android:name="com.android.myapplication.ui.detail.DetailActivity"
     android:label="DetailActivity">
     <argument
         android:name="detailId"
         app:argType="string" />
 </activity>
</navigation>

Finally, the page jumps, the parameter is passed

      val direction =  HomeFragmentDirections.actionNavigationHomeToDetailActivity(plantId)
    view.findNavController().navigate(direction)

Parameter receiving:

private val args: DetailActivityArgs by navArgs()

Databinding

Using the control directly in onCreateView () will report a null pointer exception. This gesture binding.tvNavigation is possible.

val binding = FragmentHomeBinding.inflate(inflater, container, false)
binding.tvNavigation.setOnClickListener {
            navigateToDetailPage("1", it)
        }

In the layout file, string concatenation, such as use with ViewModel:

   android:text='@{"Data From Network-> "+viewModel.response}'

ViewModel

Store and manage interface related data in a life cycle manner.

Kotlin coroutine viewModelScope, if the ViewModel is cleared, the coroutines started in this scope will be automatically canceled.

private val homeViewModel: HomeViewModel by viewModels {
        InjectorUtils.provideHomeViewModelFactory(requireContext())
    }

viewModelScope.launch {
           ...
        }

LiveData

An observable data storage class with life cycle awareness, meaning that it follows the life cycle of other application components (such as Activity, Fragment, or Service).

 var plantName = gardenPlantings.map {
        ...
    }

map implements LiveData conversion

Room

To create a cache of application data, SQLite provides an abstraction layer based on SQLite, making full use of SQLite's powerful functions and a more robust database access mechanism.

Using Room to reference complex data, Room provides the ability to convert between basic types and wrapper types, but does not allow object references between entities.

To add such support for custom types, you need to provide a TypeConverter, which can convert back and forth between the custom class and the known types that Room can retain.

class Converters {//TypeConverters    ...}

Add the @TypeConverters annotation to the AppDatabase class so that Room can use the converter you defined for each entity and DAO in the AppDatabase:

@Database(entities = table, version = 1, exportSchema = false)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {
   ...
}
@Insert
suspend fun insertPlant(plant: Plant): Long

Think of coroutine suspend

WorkManager

Using the WorkManager API, you can easily schedule deferrable asynchronous tasks that should run even when the application exits or the device restarts.

val workManagerConfiguration = Configuration.Builder()
            .setWorkerFactory(RefreshDataWork.Factory())
            .build()

 WorkManager.initialize(appContext, workManagerConfiguration)
        val constraints = Constraints.Builder()
            .setRequiresCharging(true)
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .build()

val work = PeriodicWorkRequestBuilder<RefreshDataWork>(2, TimeUnit.HOURS)
            .setConstraints(constraints)
            .build()

WorkManager.getInstance(appContext)
            .enqueueUniquePeriodicWork(RefreshDataWork::class.java.name, KEEP, work)

PeriodicWorkRequest is used for repetitive or repetitive work, the minimum interval should be 15 minutes.

OneTimeWorkRequest applies once and does not repeat work.

WorkManager is executed sequentially, in singleton mode, and executed once when the app starts.

Download address of code Github:

https://github.com/AlbertShen0211/Android-architecture-components

In order to better understand the code, the drawings are as follows

architecture.png

Published 488 original articles · praised 85 · 230,000 views +

Guess you like

Origin blog.csdn.net/Coo123_/article/details/105072377