如何修复此代码中的弃用警告?或者,还有其他的选择吗?
Handler().postDelayed({
context?.let {
//code
}
}, 3000)
如何修复此代码中的弃用警告?或者,还有其他的选择吗?
Handler().postDelayed({
context?.let {
//code
}
}, 3000)
当前回答
如果你使用变量作为处理程序和可运行的,然后像这样使用它。
private Handler handler;
private Runnable runnable;
handler = new Handler(Looper.getMainLooper());
handler.postDelayed(runnable = () -> {
// Do delayed stuff here
handler.postDelayed(runnable, 1000);
}, delay);
你还需要删除onDestroy()中的回调
@Override
public void onDestroy() {
super.onDestroy();
if (handler != null) {
handler.removeCallbacks(runnable);
}
}
其他回答
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
}
被弃用的函数是Handler的构造函数。请改用Handler(loop . mylooper ()) .postDelayed(runnable, delay)
使用这个
Looper.myLooper()?.let {
Handler(it).postDelayed({
//Your Code
},2500)
}
如果你使用变量作为处理程序和可运行的,然后像这样使用它。
private Handler handler;
private Runnable runnable;
handler = new Handler(Looper.getMainLooper());
handler.postDelayed(runnable = () -> {
// Do delayed stuff here
handler.postDelayed(runnable, 1000);
}, delay);
你还需要删除onDestroy()中的回调
@Override
public void onDestroy() {
super.onDestroy();
if (handler != null) {
handler.removeCallbacks(runnable);
}
}
协程 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()
}