androidkotlinandroid-jetpackandroid-jetpack-navigation

Is it safe to make a splash screen this way?


I have made this splash screen for my app but im not sure whether is the best option. As it is sleeping the thread when the app is launching. Here is the code, I use navigation components so the weren´t tutorials available. SplashFragment.kt

class SplashFragment : Fragment() {

private lateinit var rootview:View

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    // Inflate the layout for this fragment

    splash()
    rootview = inflater.inflate(R.layout.fragment_splash, container, false)

    return rootview
}

fun splash(){
    Thread(Runnable {
        Thread.sleep(500)
        findNavController().navigate(R.id.action_splahFragment_to_loginFragment)
    }).start()
}

}


Solution

  • Your solution is good, but it is not safe, it will anyways spawn a new Thread when you call start and that thread will sleep all good so far but you need to call navController from UI thread, also if user quits the app before 500 milliseconds it will crash.

    Here is a solution Kotlin coroutines way

    val mDelayJob: CompletableJob = Job() 
    //use mDelayJob to cancel coroutine in onStop, so if even user exits before delay, nothing will happen
    fun splash(){
        CoroutineScope(Dispatchers.Main).launch(mDelayJob){
            delay(500)
            findNavController().navigate(R.id.action_splahFragment_to_loginFragment)
        }
    }