How to delay onClick (Android)
本问题已经有最佳答案,请猛点这里访问。
对不起,我是新的Android Java。请阅读下面代码上的注释标签"/",当我单击我的按钮时,发送邮件和卸载同时工作,如何延迟?
1 2 3 4 5 6 7 8 9 10 11 | @Override public void onClick(View v) { // execute send mail first sendEmail(); // delayed 30 second then execute this uninstall. Uri packageUri = Uri.parse("package:com.naufalazkia.zitongart"); Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageUri); startActivity(uninstallIntent); } |
使用postDelayed():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | @Override public void onClick(View v) { // execute send mail first sendEmail(); v.postDelayed(new Runnable() { @Override public void run() { Uri packageUri = Uri.parse("package:com.naufalazkia.zitongart"); Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageUri); startActivity(uninstallIntent); } }, 30000L); } |
可以使用处理程序将方法延迟所需的时间。以下是如何:
1 2 3 4 5 6 7 | Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { //Your method to be executed after the delay. } }, 1000); //1000 is the time in milliseconds( 1 sec) to wait. |
你可以做到:
1 2 3 4 5 6 7 8 9 10 11 | @Override public void onClick(View v) { // execute send mail first sendEmail(); Thread.sleep(30000L);// delayed 30 second then execute this uninstall. Uri packageUri = Uri.parse("package:com.naufalazkia.zitongart"); Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageUri); startActivity(uninstallIntent); } |
但是睡眠线程并不是一个好的开发实现,相反,您可以重构一些模块并等待一些回调或通知。