Headertab

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Tuesday 30 October 2018

How to ON/OFF battery doze mode in android

Hello, dear friends, this post is very important to the Android developers to resolve to avoid battery doze mode so let's start...


MainActivity.java

package com.samset.doze;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatTextView;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.samset.doze.utils.DozeHelper;

public class MainActivity extends AppCompatActivity {
    private AppCompatButton btncheck;
    private AppCompatTextView tvmsg;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btncheck=findViewById(R.id.btncheck);
        tvmsg=findViewById(R.id.tvmsg);


        tvmsg.setText("This app is " +DozeHelper.getisBatteryOptimizations(this,getPackageName().toString()));
        btncheck.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                Intent intent= DozeHelper.prepareBatteryOptimization(MainActivity.this,getPackageName(),true);
                startActivity(intent);

            }
        });





    }
}

DozeHelper.java

public class DozeHelper {


    public enum PowerSaveState {
        ON, OFF, ERROR_GETTING_STATE, IRRELEVANT_OLD_ANDROID_API    }

    public enum WhiteListedInBatteryOptimizations {
        WHITE_LISTED, NOT_WHITE_LISTED, ERROR_GETTING_STATE, UNKNOWN_TOO_OLD_ANDROID_API_FOR_CHECKING, IRRELEVANT_OLD_ANDROID_API    }

    public enum DozeState {
        NORMAL_INTERACTIVE, DOZE_TURNED_ON_IDLE, NORMAL_NON_INTERACTIVE, ERROR_GETTING_STATE, IRRELEVANT_OLD_ANDROID_API, UNKNOWN_TOO_OLD_ANDROID_API_FOR_CHECKING    }

    @NonNull    public static DozeState getDozeState(@NonNull Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
            return DozeState.IRRELEVANT_OLD_ANDROID_API;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return DozeState.UNKNOWN_TOO_OLD_ANDROID_API_FOR_CHECKING;
        }
        final PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (pm == null)
            return DozeState.ERROR_GETTING_STATE;
        return pm.isDeviceIdleMode() ? DozeState.DOZE_TURNED_ON_IDLE : pm.isInteractive() ? DozeState.NORMAL_INTERACTIVE : DozeState.NORMAL_NON_INTERACTIVE;
    }

    @NonNull    public static PowerSaveState getPowerSaveState(@NonNull Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
            return PowerSaveState.IRRELEVANT_OLD_ANDROID_API;
        final PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (pm == null)
            return PowerSaveState.ERROR_GETTING_STATE;
        return pm.isPowerSaveMode() ? PowerSaveState.ON : PowerSaveState.OFF;
    }


    @NonNull    public static WhiteListedInBatteryOptimizations getisBatteryOptimizations(@NonNull Context context, @NonNull String packageName) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
            return WhiteListedInBatteryOptimizations.IRRELEVANT_OLD_ANDROID_API;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
            return WhiteListedInBatteryOptimizations.UNKNOWN_TOO_OLD_ANDROID_API_FOR_CHECKING;
        final PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (pm == null)
            return WhiteListedInBatteryOptimizations.ERROR_GETTING_STATE;
        return pm.isIgnoringBatteryOptimizations(packageName) ? WhiteListedInBatteryOptimizations.WHITE_LISTED : WhiteListedInBatteryOptimizations.NOT_WHITE_LISTED;
    }

    @TargetApi(Build.VERSION_CODES.M)
    @RequiresPermission(Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
    @Nullable    public static Intent prepareBatteryOptimization(@NonNull Context context, @NonNull String packageName, boolean alsoWhenWhiteListed) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
            return null;
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) == PackageManager.PERMISSION_DENIED)
            return null;
        final WhiteListedInBatteryOptimizations ispowersave = getisBatteryOptimizations(context, packageName);
        Intent intent = null;
        switch (ispowersave) {
            case WHITE_LISTED:
                if (alsoWhenWhiteListed)
                    intent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
                break;
            case NOT_WHITE_LISTED:
                intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).setData(Uri.parse("package:" + packageName));
                break;
            case ERROR_GETTING_STATE:
            case UNKNOWN_TOO_OLD_ANDROID_API_FOR_CHECKING:
            case IRRELEVANT_OLD_ANDROID_API:
            default:
                break;
        }
        return intent;
    }

    /**     * registers a receiver to listen to power-save events. returns true if succeeded to register the broadcastReceiver.     */    @TargetApi(Build.VERSION_CODES.M)
    public static boolean registerPowerSaveReceiver(@NonNull Context context, @NonNull BroadcastReceiver receiver) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
            return false;
        IntentFilter filter = new IntentFilter();
        filter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
        context.registerReceiver(receiver, filter);
        return true;
    }


}


Enjoy with code




Saturday 20 October 2018

WorkManager jetpack in android

Hello, guys today I goes to write about android new library Jetpack component WorkManager.

 What is WorkManager?

 Workmanager is part of Android Jetpack library and an Architecture Component for background work that needs a combination of opportunity and guaranteed execution. WorkManager will take care of the care of the logic to start your work under a variety of situations, even if you navigate away from your app.

WorkManager is a flexible library that has many additional features ...

 1: Support for both asynchronous one-off and periodic tasks.
 2: Support for constraints such as network condition, storage space, and charging status
 3: Chaining of complex work requests, including running work in parallel.
 4: Output from one work request used as input for the next.
 5: Handles API level compatibility back to API level 14.
 6: Work with or without google play services
 7: Follow system health best practice.
 8: LiveData support to easily display work request state in UI.


WorkManager Components

WorkManager: Receives the work with specific arguments and enqueues that work.

Worker: Implements doWork() which executes the functionality on the background thread.

WorkRequest: Represent an individual task. It will tell you which Worker is enqueued as well as what contents it needs to meet in order for it to run. WorkRequest is an abstract class that you will be using with OneTimeWorkRequest or PerodicWorkRequest.

WorkStatus: Provide data for each WorkRequest Object.


Let's start

MainActivity.kt


class MainActivity : AppCompatActivity(),View.OnClickListener {


    private var TAG: String = MainActivity::class.java.simpleName
    private lateinit var workManager: WorkManager
    private lateinit var timeWorkRequest: OneTimeWorkRequest
    private lateinit var periodicWorkRequest: PeriodicWorkRequest

    private  var PERIODIC_REQUEST_TAG:String="periodic_request"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        workManager = WorkManager.getInstance()!!
        btnstart.setOnClickListener(this)
        btnstop.setOnClickListener(this)


    }

    private fun setupOneTimeWorker() {
        timeWorkRequest = OneTimeWorkRequest.Builder(MyWorker::class.java)?.build()
        workManager.enqueue(timeWorkRequest)
    }

    private fun setupPeriodicWorker() {

        val works = WorkManager.getInstance().getStatusesByTag(PERIODIC_REQUEST_TAG)

        if (works.value != null && works.value?.isNotEmpty()!!) {
            return        }

        val work = PeriodicWorkRequest.Builder(MyWorker::class.java, PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS, TimeUnit.MINUTES, PeriodicWorkRequest.MIN_PERIODIC_FLEX_MILLIS, TimeUnit.MINUTES)
        periodicWorkRequest = work.build()

         workManager.enqueue(periodicWorkRequest)

    }

    private fun requestPerodicWorkerSecondMethod(){
        val statusesByTag = workManager.getStatusesByTag(PERIODIC_REQUEST_TAG)
        if (statusesByTag == null || statusesByTag.value?.size == 0) {

        } else {
            for (i in 0 until statusesByTag.value?.size!!) {
                Log.e("TAG", " perodic request id " + statusesByTag.value?.get(i)?.id + " Status " + statusesByTag.value?.get(i)?.state)
            }
        }
    }


    override fun onClick(view: View?) {
        if (view == btnstart) {
            setupOneTimeWorker()
        } else if (view == btnstop) {
            setupPeriodicWorker()
            // or           // requestPerodicWorkerSecondMethod()        }

    }
}

MyWorker.kt


class MyWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
    private val TAG: String = MyWorker::class.java.simpleName
    override fun doWork(): Result {

        sendNotification("Title", "Details")
        return Result.SUCCESS
    }


    fun sendNotification(title: String, message: String) {
        val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        //If on Oreo then notification required a notification channel.        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            val channel = NotificationChannel("default", "Default", NotificationManager.IMPORTANCE_DEFAULT)
            notificationManager.createNotificationChannel(channel)
        }

        val notification = NotificationCompat.Builder(applicationContext, "default")
                .setContentTitle(title)
                .setContentText(message)
                .setSmallIcon(R.mipmap.ic_launcher)

        notificationManager.notify(1, notification.build())
    }

}


Thank you
Full Source code WorkManager-jetpack


Nougat and oreo notification



String channelId = "default";
String title = context.getString(R.string.app_name);

PendingIntent pendingIntent = PendingIntent.getActivity(context, 101, intent, PendingIntent.FLAG_UPDATE_CURRENT);

// Foreground Notification ContextNotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);

Notification notification = notificationBuilder
        .setContentTitle(title)
        .setSmallIcon(android.R.drawable.btn_star)
        .setContentText("Alarm Counter")
        .setAutoCancel(true)
        .setContentIntent(pendingIntent)
        .setWhen(System.currentTimeMillis())
        .build();

// Notification Channelif (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    NotificationChannel channel = new NotificationChannel(channelId, title, NotificationManager.IMPORTANCE_DEFAULT);
    channel.setDescription("Silent Notification");
    channel.setSound(null, null);
    channel.enableLights(false);
    channel.setLightColor(Color.BLUE);
    channel.enableVibration(false);
    notificationManager.createNotificationChannel(channel);

}
startForeground(1, notification);

FirebaseDispatcher android sample

Hello, guys today we learn about what is FirebaseDispatcher and how to use our android project but before know about FirebaseRequestDispatcher, we know about JobScheduler.

What is JobScheduler?

The job scheduler is an android system service available on API level 21(Lollypop). It provides an  API for scheduling unit of work that will executed in your app process.

FirebaserequestDispatcher

The firebase jobDispatcher is a library for scheduling jobs in your android app. It provides a JobScheduler compatible API that works on all recent version of Android( API 14) that have google play service installed.


Dependency

 Add following line in your project build.gradle's dependencies section

implementation 'com.firebase:firebase-jobdispatcher:0.8.5'
How to use?

Simple extends with JobService class the JobService by default used Service class

import com.firebase.jobdispatcher.JobParameters;
import com.firebase.jobdispatcher.JobService;

public class MyJobService extends JobService {
    @Override
    public boolean onStartJob(JobParameters job) {
        // Do some work here
        return false; // Answers the question: "Is there still work going on?"
    }

    @Override
    public boolean onStopJob(JobParameters job) {
        return false; 
    }
}

Now create a simple dispatcher class and initialize google play driver

FirebaseJobDispatcher dispatcher =
    new FirebaseJobDispatcher(new GooglePlayDriver(context));


See source code 

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String JOB_TAG = "MyJobService";
    private FirebaseJobDispatcher mDispatcher;


    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btnstart).setOnClickListener(this);
        findViewById(R.id.btnstop).setOnClickListener(this);

        mDispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
    }

    @Override    public void onClick(View view) {
        int id = view.getId();
        if (R.id.btnstart == id) {
            scheduleJob();
        } else {
            cancelJob(JOB_TAG);
        }
    }


    private void scheduleJob() {
        Job myJob = mDispatcher.newJobBuilder()
                .setService(MyJobService.class) //  your job class name                .setTag(JOB_TAG) // define your tag name                .setRecurring(true)
                .setTrigger(Trigger.executionWindow(5, 60)) // trigger job every 1 min                .setLifetime(Lifetime.UNTIL_NEXT_BOOT)
                .setReplaceCurrent(false) // if you want when open your app then job auto replace with new job then this flag make true                .setConstraints(Constraint.ON_ANY_NETWORK)
                .setRetryStrategy(RetryStrategy.DEFAULT_LINEAR) // this is trigger linear time inteval like.. 1min,2min,3min,4min....                .build();
        mDispatcher.mustSchedule(myJob);
        Toast.makeText(this, "job_scheduled", Toast.LENGTH_LONG).show();
    }

    // cancel job    private void cancelJob(String jobTag) {
        if ("".equals(jobTag)) {
            mDispatcher.cancelAll();
        } else {
            mDispatcher.cancel(jobTag);
        }
        Toast.makeText(this, "job_cancelled", Toast.LENGTH_LONG).show();
    }
}

MyJobService.java


public class MyJobService extends JobService {
    private int ii = 0;
    private static final String TAG = "MyJobService";

    @Override    public boolean onStartJob(JobParameters jobParameters) {
        String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
        Log.e(TAG, "Job " + currentDateTimeString);
        sendNotification("DispatcherRequest","Current noti "+currentDateTimeString);
        return false;
    }

    @Override    public boolean onStopJob(JobParameters jobParameters) {
        Log.e(TAG, "Job cancelled!");
        return false;
    }


    private void sendNotification(String contentTitle, String message) {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        //notificationManager.cancelAll();

        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);


        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String channelId = "default_notification_channel_id";
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle(contentTitle)
                        .setContentText(message)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);


        // Since android Oreo notification channel is needed.        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId, "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(1 /* ID of notification */, notificationBuilder.build());
    }


}


Thank you
enjoy with this source code

Full Source Code FirebaseJobDispatcher










Thursday 16 August 2018

Scanner animation in android

Hello, dear friends if you want to create scanner animation with shape design then follow this steps.


Create drawable file name of line_shape.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="line">
            <solid android:color="#0000FF" />
            <size
                android:width="480dp"
                android:height="10dp" />
            <corners android:radius="1dp" />
            <stroke
                android:width="3dp"
                android:color="#000000" />
        </shape>
    </item>
    <item android:top="30dp">
        <shape android:shape="line">
            <solid android:color="#0000FF" />
            <size
                android:width="480dp"
                android:height="10dp" />
            <corners android:radius="1dp" />
            <stroke
                android:width="3dp"
                android:color="#000000" />
        </shape>
    </item>
    <item android:top="60dp">
        <shape android:shape="line">
            <solid android:color="#0000FF" />
            <size
                android:width="480dp"
                android:height="10dp" />
            <corners android:radius="1dp" />
            <stroke
                android:width="3dp"
                android:color="#000000" />
        </shape>
    </item>

</layer-list>

MainActivity.java


private ImageView ivscanner;



onCreate(Bundle saveinstance){
 setContentView(R.layout.mainactivity);

startScan();


}





public void startScan(){

ivscanner.setVisibility(View.VISIBLE);
mAnimation = new TranslateAnimation(
        TranslateAnimation.ABSOLUTE, 0f,
        TranslateAnimation.ABSOLUTE, 0f,
        TranslateAnimation.RELATIVE_TO_PARENT, 0f,
        TranslateAnimation.RELATIVE_TO_PARENT, 1.0f);
mAnimation.setDuration(9000);
mAnimation.setRepeatCount(-1);
mAnimation.setRepeatMode(Animation.REVERSE);
mAnimation.setInterpolator(new LinearInterpolator());
ivscanner.setAnimation(mAnimation);

}















Wednesday 11 July 2018

Difference between run, with, let, also and apply in kotlin

Hello dear friends today we are learn about what difference in run, with, let, also and apply . This is master function of the kotlin.

Kotlin  let: 

let take the object is invoked upon as the parameter and return the result of the lambda expression. In other word we also said let is a non-nomadic version of map. It is accept the object as a parameters and returns the result of the lambda. like...

Example 1: 
var student= Student("samset",100)
var result = student.let{ it.rollno=50}

Log.e(" student roll no : "+student)
Log.e("result student roll no : "+result)

OUTPUT:
100
50

here it keyword copy of the property inside the let. let function scope only inside the expression cannot be used outside of the expression.

Example 2: 

 var strlength = str.let { "$it my function".length}
 println("strlength is $strlength") // strlength is 30


class MyTestClass{

   fun testfunction(){
     val str : String = "welcome to kotlin"
     val myresult = str.let{
      
    print(this) // this is instance of MyTestClass 
    print(it)   // it is the  String = "welcome to kotlin" on which we have called let

}
}
}

Chaining let functon:


val strmain="welcome"

// Evolve the value and send to the next chain
 strmain.let{
   println("This is main original string $it") // "welcome"
   it.reversed() // evolve it as parameter to send to next let
}.let{
println("This is reverse string $it") // "emoclew"
it.length   // evolve it as parameter to next let
}.let{
   println("The length of string is $it")  // 7
}

 Outer let:
After nested let used now we are use outer let:

var str="Smaset"
     
      str = str.let{ outer->
        
        outer.let{ inner->
                println(" Inner let is "$inner)
      }
     "Outerlet is $outer"
      }

    println(str)


OUTPUT:

Inner let is samset
Outer let is samset

let check Null:

    var strmain = String? = "welcome"
   strmain ?.let{ println(it)}  // prints welcome
 
    strmain =null
    strmain ?.let{ println(it)} // nothing happens

Kotlin run:

Kotlin run is another interesting function. The following example demonstrates its use cases. run does not return values and does not support it keyword.
var str  =  "Hello welcome to kotlin"
    println(str) //  "Hello welcome to kotlin"
      val str  = "This is a run function" str
}
println(str) // This is a run function

OUTPUT:
  Hello welcome to kotlin
   This is a run function


let with run

      var mytext : String? = null
     
    p?.let{ println(" Text is $mytext ")} ?:
        run { println("Text was null so set default value :"+ mytext ="Default text")}

        println(mytext)


OUTPUT:

Text was null so set default value : Default text 

Kotlin let vs also
also is something same like let but this is return only original value. Rhe also expression return the data class object whereas th let expression return nothing (Unit) as we didn't specify anything explicitly see example for understanding...


   data class Student(var name: String,var rollno : int)
   var stud  = Student("Samset",101)
   
   var s  =  stud.let{ it.name = "sanjoo"}
   var salso  =  stud.also{ it.name = "sanjoo"}

println(s)
println(salso)
println(stud)

OUTPUT:

sanjoo
sanjoo


























Friday 6 July 2018

Jetpack Navigation

Hello guys today we are learn about how to manage fragment navigation with jetpack library but before learn about navigation first you learn about What is Jetpack library?.


JetPack:
Android JetPack is a set of android components designed with Kotlin in mind, available with Android Studio 3.2.


Google’s annual I/O developer conference is where the company unveils their latest tools and features for Android developers, and this year is no exception. Today, the company announced Android Jetpack, a set of components to accelerate app development. Jetpack is designed with Kotlin in mind to help you simplify your code. The latest Android Studio 3.2 canary available today also features new tools for Jetpack.

Accelerating app development with Android JetPack

Android Jetpack is a set of Android components, tools, and guidance inspired by the backward compatibility of the Support Library and the ease of use of the Android Architecture Components. Jetpack components can broadly be categorized into four categories: Architecture, UI, Foundation, and Behavior.
Architecture components include activities like lifecycle management, ViewModel, data binding, and more. UI components include animation and transitions, fragments, layouts, and more. Foundation components include AppCompat, Multidex, testing, and more. Behavior components include media and playback, permissions, notifications, sharing and more.





WorkManager

This library provides an API for constraint-based background jobs that must be executed, replacing the need for jobs or SyncAdapters. It works on devices without Google Play Services, can create graphs of work, and can query the state of your work.

Navigation

Many applications are composed of multiple activities, but sharing data between activities and implementing transitions has been a pain-point for in-app navigation. The Navigation component will help you structure your in-app user interface as a single-Activity app. It supports Fragments out of the box so all the benefits of Architecture Components such as Lifecycle and ViewModel are there while the Navigation component handles FragmentTransitions for you. Furthermore, you can declare transitions that Navigation will automatically handle, you can build with the correct Up and Back behavior automatically, you can easily provide full support for deep links, and you can connect Navigation to UI widgets like the navigation drawer and bottom navigation. Lastly, the Navigation Editor in the latest Android Studio allows you to visually manage navigation properties

Paging

The Paging component, when combined with RecyclerView, allows you to add fast, infinite scrolling to your app. The idea is that the component simplifies managing data in pages, ie. pulling chunks of data in succession as quickly as possible and returning results for the user to view.

Slices

Lastly, the Slices component will simplify the process of implementing the Slices API introduced with Android P. It’s an API that lets you surface your app’s UI inside of the Google App as a search result.

Now you create a sample project and follow  below instructions :
If you had create new project then add these two line dependency and two line top of gradle in app level gradle like..

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'androidx.navigation.safeargs'
implementation 'android.arch.navigation:navigation-fragment-ktx:1.0.0-alpha02'
implementation 'android.arch.navigation:navigation-ui-ktx:1.0.0-alpha02'

Complete gradle file like :
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'androidx.navigation.safeargs'
android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.samset.jetpacknavigation"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.0-alpha1'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.0'
    implementation 'android.arch.navigation:navigation-fragment-ktx:1.0.0-alpha02'
    implementation 'android.arch.navigation:navigation-ui-ktx:1.0.0-alpha02'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0-alpha1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha3'
}
and project level gradle look like this 
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext.kotlin_version = '1.2.50'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.0-alpha18'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'android.arch.navigation:navigation-safe-args-gradle-plugin:1.0.0-alpha02'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
allprojects {
    repositories {
        google()
        jcenter()
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}
and now open open gradle.properties file and paste these two line

android.enableJetifier=trueandroid.useAndroidX=true

And now you create navigation xml
First you right click on res folder and create new resource file and now select resource type is "Navigation" and enter file name navigation_graph and press OK


Create tow or three fragment and follow some instructions

FragmentOne.kt

class FragmentOne : Fragment() {
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_fragment_one, container, false)
    }
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        /*
        * here i am navigate(transaction fragment first to second)
        * fragment with direction function you can choose another function
        * you can see second fragment tranction i am use another funtions for the transaction
        *
        * */
        btnNext1.setOnClickListener{
            var directions=FragmentOneDirections.action_fragmentSecond()
            // if you send data in bundle you can pass directly here
            directions.setMydata("Hello I am passed data from fragment one")
            var  controller=it.findNavController()
            controller.navigate(directions)
        }
    }
}

In FragmentOne i am use simple fragment transaction and you can pass data.

FragmentSecond.kt

class FragmentSecvond : Fragment() {
    internal var infos = User()
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_fragment_secvond, container, false)
    }
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        arguments?.let {
            var values=FragmentSecvondArgs.fromBundle(it)
            tvnames.text=values.mydata
        }
        /*
        * here i am set custom data in bundle with seralizable
        * */
        btnNext2.setOnClickListener{
            infos.username=" i am samset"
            infos.mobilenumber="98110540xxx"
            val bundle = Bundle()
            bundle.putSerializable("data",infos)
            val navController = it.findNavController()
            navController.navigate(R.id.fragmentThird,bundle)
        }
    }
}

In secondfragment you can see how to pass custom serialisable data to thirdfragment.


NOTE:-
If you want Maintain fragment backstack then override this method in your MainActivity

override fun onSupportNavigateUp()=findNavController(R.id.mainNavigationFragment).navigateUp()


If you want  not maintain the backstack specific fragment then you add one line of code in navigation_graph like..

<fragment
    android:id="@+id/fragmentSecvond"
    android:name="com.samset.jetpacknavigation.fragments.FragmentSecond"
    android:label="fragment_fragment_secvond"
    tools:layout="@layout/fragment_fragment_secvond">
    <argument
        android:name="mydata"
        android:defaultValue="defaulttext"
        app:type="string" />
    <action
        android:id="@+id/action_fragmentSecvond_to_fragmentThird"
        app:clearTask="true"   // add this line for clear backstack
        app:destination="@id/fragmentThird" />

</fragment>

You can also be change the action "Pop To" behavior from attribute pannel( from xml app:popUpTo="@+id/FragmentOne). This way when user will click back, he will be navigated to FragmentOne instead of the original destination.

<fragment
    android:id="@+id/fragmentThird"
    android:name="com.samset.jetpacknavigation.fragments.FragmentThird"
    android:label="fragment_fragment_third"
    tools:layout="@layout/fragment_fragment_third">
    <action
        android:id="@+id/action_fragmentThird_to_fragmentFourth"
        app:destination="@id/fragmentFourth" />
    <action
        app:popUpTo="@id/action_fragmentSecond" // add this line and change pop to destination
        android:id="@+id/action_fragmentThird_to_fragmentOne"
        app:destination="@id/fragmentOne" />

</fragment>


Thank you

Full SourceCode JetPack-Navigation