如何修复此代码中的弃用警告?或者,还有其他的选择吗?

Handler().postDelayed({
    context?.let {
        //code
    }
}, 3000)

当前回答

import android.os.Looper
import android.os.Handler

inline fun delay(delay: Long, crossinline completion: () -> Unit) {
    Handler(Looper.getMainLooper()).postDelayed({
        completion()
    }, delay)
}

例子:

delay(1000) {
    view.refreshButton.visibility = View.GONE
}

其他回答

协程 Kotlin

private val SPLASH_SCREEN_TIME_OUT_CONST: Long = 3000

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_splash)
    window.setFlags(
        WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN
    )
    GlobalScope.launch {
        delay(SPLASH_SCREEN_TIME_OUT_CONST)
        goToIntro()
    }

}

private fun goToIntro(){
    startActivity(Intent(this, IntroActivity::class.java))
    finish()
}

使用生命周期范围会更容易。内部活动或片段。

 lifecycleScope.launch {
     delay(2000)
     // Do your stuff
 }

或者使用处理器

        Handler(Looper.myLooper()!!)

Handler()和Handler(Handler.)回调回调)构造函数已弃用。因为这可能会导致bug和崩溃。显式使用Executor或Looper。

对于Java

Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
  @Override
  public void run() {
    //do your work here
   }
}, 1000);

使用Executor而不是handler获取更多信息。 使用ScheduledExecutorService实现post delay:

ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
Runnable runnable = () -> {
    public void run() {
        // Do something
    }
};
worker.schedule(runnable, 2000, TimeUnit.MILLISECONDS);

对于Xamarin Android,而不是

Handler handler;
handler = new Handler();

只写

Handler handler;
handler = new Handler(Looper.MyLooper());

其余的代码都很好。