我希望能在指定的延迟时间后调用下面的方法。 在Objective-C中,有一个类似于以下代码的方法:
[self performSelector:@selector(DoSomething) withObject:nil afterDelay:5];
在安卓Java中是否有此方法的等效方法?例如,我需要在5秒后调用一个方法。
public void DoSomething()
{
//do something here
}
关于活动类的另一个响应(Java8)。
//hide with delay
new Thread(() -> {
try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}
this.runOnUiThread(() -> {
myView.setVisibility(View.GONE);//this run on GUI
});
}).start();
如果你在使用Java,那么你总是可以使用传统的Thread.sleep()
。
new Thread(() -> {
try {
Thread.sleep(millis); //delay in milliseconds
} catch (Exception e) {
e.printStackTrace();
}
yourMethod();
}).start();
类似的解决方案,但使用起来更加简洁
将此函数写在类外面
fun delay(duration: Long, `do`: () -> Unit) {
Handler().postDelayed(`do`, duration)
}
使用方法:
delay(5000) {
//Do your work here
}
有很多方法可以做到这一点,但最好的方法是使用以下处理程序
long millisecDelay=3000
Handler().postDelayed({
// do your work here
},millisecDelay)
Android中的合适解决方案:
private static long SLEEP_TIME = 2 // for 2 second
.
.
MyLauncher launcher = new MyLauncher();
launcher.start();
.
.
private class MyLauncher extends Thread {
@Override
/**
* Sleep for 2 seconds as you can also change SLEEP_TIME 2 to any.
*/
public void run() {
try {
// Sleeping
Thread.sleep(SLEEP_TIME * 1000);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
//do something you want to do
//And your code will be executed after 2 second
}
}
class MainActivity : AppCompatActivity() {
private lateinit var handler: Handler
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
handler= Handler()
handler.postDelayed({
doSomething()
},2000)
}
private fun doSomething() {
Toast.makeText(this,"Hi! I am Toast Message",Toast.LENGTH_SHORT).show()
}
}
do
是内置方法,因此我们必须使用`来将其用作变量名。 - Manohardo
操作 - Manohar