Android can not miss learning! You see Android Jetpack best development posture!

Android Jetpack best development posture

In the Androidarchitectural components based on the integration of Kotlincoroutines +retrofit, network simulation, comprehensive and rapid development.

Navigation

NavControllerIn NavHostthe application of the navigation management object, along a specific route map navigate to a specific target, or to navigate directly to a specific destination.

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, the definition navigation/mobile_navigation.xml Activityof the addition, the need to Projectcreate the corresponding Activitycan handle 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, parameter passing

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

Reception parameters:

    private val args: DetailActivityArgs by navArgs()

Databinding

In onCreateView()use direct controls, will be reported null pointer exception, this position binding.tvNavigationis possible.

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

Layout files, string concatenation, as now ViewModelused with:

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

ViewModel

To store and manage the life cycle of interface-related data. KotlinCoroutine viewModelScope, if ViewModelcleared, it is in this range start coroutine will be automatically canceled.

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

  viewModelScope.launch {
             ...
          }

LiveData

An observation data store class, with the life cycle of perception, meaning that it follows the other application components (e.g. Activity, Fragmentor Service) lifecycle.

     var plantName = gardenPlantings.map {
          ...
      }

mapAchieve LiveDataconversion

Room

Create a cache application data, SQLiteit provides a layer of abstraction based on the full use SQLiteof the powerful, more robust database access mechanism.

Use Roomreference complex data, Roomprovides the function of conversion between the package and the type of basic types, but does not allow object references between entities.

To add such support custom type, you need to provide a TypeConverter, it can be a custom class and Roomswitch back and forth between the known types can be reserved.

  class Converters {//TypeConverters
      ...
  }

To @TypeConvertersadd comments to AppDatabasethe class, so that Roomyou can use for your AppDatabaseeach entity and DAOdefined Converter:

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

Considered coroutinesuspend

WorkManager

Use WorkManager APIcan easily schedule even when the application exits or equipment restart delay should still be running asynchronous tasks.

  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)

PeriodicWorkRequestFor repeating or duplicating the work, the minimum spacing should be 15 minutes.

OneTimeWorkRequestOne-time application, without duplication of effort.

WorkManagerExecuted in order, singleton, appperform a startup.

Third, the summary

For advanced this way, the learning will pay off!

You take your time to invest in learning, it means that you can gain skills, have the opportunity to increase revenue.

I enclose my Android core technology learning syllabus, access to relevant content to play with my GitHub: https://github.com/Meng997998/AndroidJX

Share my Android PDF Daquan learn to learn, learn this Android PDF Daquan really contain all aspects, and contains basic Java knowledge, the basis of Android, Android Advanced extension, and so on collection algorithm

My collection this study, can effectively help you grasp the knowledge points.

In short we are also here to help enhance learning advanced, but also saves you the time to learn online search data can also be shared with close friends studying together

Published 168 original articles · won praise 71 · views 20000 +

Guess you like

Origin blog.csdn.net/Aerfa789/article/details/104954542