【问题标题】:How to delay onClick (Android) [duplicate]如何延迟onClick(Android)[重复]
【发布时间】:2016-05-17 04:03:24
【问题描述】:

对不起,我是 android java 的新手。请阅读下面代码中的注释标签“//”,当我点击我的按钮时,发送邮件和卸载同时进行,如何延迟?

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

【问题讨论】:

    标签: android


    【解决方案1】:

    使用 postDelayed():

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

    【讨论】:

    • 谢谢,喜欢这个方法:v
    【解决方案2】:

    您可以使用处理程序将方法延迟所需的时间。方法如下:

    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.
    

    【讨论】:

      【解决方案3】:

      你可以这样做:

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

      但是睡眠线程不是一个好的开发实现,相反你可以重构一些模块并等待一些回调或通知。

      【讨论】:

      • 这里的问题不在于延迟本身,而是延迟发生在主 UI 线程上应用挂起。
      猜你喜欢
      • 2016-04-04
      • 2013-04-19
      • 2011-05-11
      • 2013-04-08
      • 1970-01-01
      • 2013-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多