Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Android Jetpack Joyride

Android Jetpack Joyride

It includes four components of Android Jetpacks. It includes Room, Paging Library, WorkManager, Palette, Slice etc.

Krunal Kapadiya

October 28, 2018
Tweet

More Decks by Krunal Kapadiya

Other Decks in Technology

Transcript

  1. What is Jetpack Jetpack is a collection of Android software

    components to make it easier for you to develop great Android apps
  2. Data Binding Life Cycles LiveData Navigation Paging Room ViewModel WorkManager

    AppCompat Android KTX Multidex Test Animations & Transitions Auto TV & Wear Emoji Fragment Layout Palette Download Manager Media & Playback Permissions Notifications Sharing Slices
  3. //activity_main.xml <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"

    tools:context=".MainActivity"> <fragment android:id="@+id/my_nav_host_fragment" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="match_parent" android:layout_height="match_parent" app:defaultNavHost="true" app:navGraph="@navigation/nav_graph" /> </android.support.constraint.ConstraintLayout> Navigation
  4. Navigation enterAnim: the animation for the target fragment/activity when we

    navigate to it exitAnim: the animation for the source fragment/activity when we navigate away from it popEnterAnim: the animation for the target fragment/activity when we press back popExitAnim: the animation for the source fragment/activity when we press back
  5. //app.gradle implementation "android.arch.persistence.room:runtime:1.1.1" annotationProcessor "android.arch.persistence.room:compiler:1.1.1" // Lifecyles, LiveData and ViewModel

    implementation "android.arch.lifecycle:runtime:1.1.1" implementation "android.arch.lifecycle:extensions:1.1.1" annotationProcessor "android.arch.lifecycle:compiler:1.1.1" Room //Movie.kt @Entity(tableName = TABLE_MOVIE) data class Movie(@PrimaryKey val id: Long, val title: String, val popularity: Int, val voteAverage: Int, val posterUrl: String, val description: String)
  6. //MoviesDao @Dao interface MoviesDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(movieList:

    List<Movie>) @Query(SELECT_MOVIE) fun allMovies(): DataSource.Factory<Int, Movie> } Room
  7. //MoviesDatabase @Database(entities = [Movie::class], version = DATABASE_MOVIE_VERSION) abstract class MoviesDatabase

    : RoomDatabase() { abstract fun movieDao(): MoviesDao companion object { @Volatile private var INSTANCE: MoviesDatabase? = null fun getInstance(context: Context): MoviesDatabase = INSTANCE ?: synchronized(this) { INSTANCE ?: buildMoviesDatabase(context).also { INSTANCE = it } } private fun buildMoviesDatabase(context: Context) = Room.databaseBuilder(context,MoviesDatabase::class.java, DATABASE_MOVIE) .build() } } Room
  8. //MoviesViewModel class MoviesViewModel(private val moviesRepository: MoviesRepository) : ViewModel() { private

    val compositeDisposable = CompositeDisposable() var pagedListMovie = MutableLiveData<PagedList<Movie>>() fun getMovies() { compositeDisposable.add(moviesRepository.fetchOrGetMovies() .subscribe({ pagedListMovie.value = it }, { it.printStackTrace() })) } override fun onCleared() { super.onCleared() compositeDisposable.dispose() } } Paging
  9. // creating instance WorkManager workManager = WorkManager.getInstance(); WorkManager // how

    to use it WorkRequest request = new OneTimeWorkRequest.Builder(FooWorker.class).build(); workManager.enqueue(request); LiveData<WorkStatus> status = workManager.getStatusByIdLiveData(request.getId()); status.observe(...); //How to cancel workManager.cancelWorkById(request.getId()); // Can also add chain WorkRequest request1 = new OneTimeWorkRequest.Builder(FooWorker.class).build(); WorkRequest request2 = new OneTimeWorkRequest.Builder(BarWorker.class).build(); WorkRequest request3 = new OneTimeWorkRequest.Builder(BazWorker.class).build(); workManager.beginWith(request1, request2).then(request3).enqueue();
  10. Palette //App gradle implementation 'com.android.support:palette-v7:28.0.0' // Our class // Generate

    palette synchronously and return it fun createPaletteSync(bitmap: Bitmap): Palette = Palette.from(bitmap).generate() // Generate palette asynchronously and use it on a different // thread using onGenerated() fun createPaletteAsync(bitmap: Bitmap) { Palette.from(bitmap).generate { palette -> // Use generated instance } }
  11. Slices A “slice” is a way to surface your app’s

    UI inside of the Google Assistant as a result of a search. Some advantages using Slices API: - Templated - Interactive
  12. Slices //MySliceProvider.java public class MySliceProvider extends SliceProvider { @Override public

    boolean onCreateSliceProvider() { return true; } public Slice onBindSlice(Uri sliceUri) { switch(sliceUri.getPath()) { case "/temperature": return createTemperatureSlice(sliceUri); } return null; } @Nullable private Slice createTemperatureSlice(Uri sliceUri) { // TODO: complete in a later step. return null; } }
  13. Slices //manifest.xml <application ... <!-- To provide slices you must

    define a slice provider --> <provider android:authorities="com.android.example.slicecodelab" android:name=".MySliceProvider" android:exported="true"> </provider> ... </application>
  14. Slices //MySliceProvider.java private Slice createTemperatureSlice(Uri sliceUri) { // Construct our

    parent builder ListBuilder listBuilder = new ListBuilder(getContext(), sliceUri, ListBuilder.INFINITY); // Construct the builder for the row ListBuilder.RowBuilder temperatureRow = new ListBuilder.RowBuilder(listBuilder); // Set title temperatureRow.setTitle(MainActivity.getTemperatureString(getContext())); // TODO: add actions to row; in later step // Add the row to the parent builder listBuilder.addRow(temperatureRow); // Build the slice return listBuilder.build(); }
  15. Make interactive slices //MySliceProvider.java SliceAction tempUp = new SliceAction(getChangeTempIntent(MainActivity.sTemperature +

    1), IconCompat.createWithResource(getContext(), R.drawable.ic_temp_up), "Increase temperature"); SliceAction tempDown = new SliceAction(getChangeTempIntent(MainActivity.sTemperature - 1), IconCompat.createWithResource(getContext(), R.drawable.ic_temp_down), "Decrease temperature");
  16. Android KTX And last but not least, one goal of

    Android Jetpack takes advantage of Kotlin language features that make you more productive.
  17. Android KTX view.viewTreeObserver.addOnPreDrawListener( object : ViewTreeObserver.OnPreDrawListener { override fun onPreDraw():

    Boolean { viewTreeObserver.removeOnPreDrawListener(this) actionToBeTriggered() return true } });