Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

android - 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()
}

}

question from:https://stackoverflow.com/questions/66057439/is-it-safe-to-make-a-splash-screen-this-way

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...