【问题标题】:Compare two time continously in android在android中连续比较两次
【发布时间】:2016-03-26 14:16:48
【问题描述】:

我想每隔一段时间在 Android 中运行 Async Task。

我的间隔是 = { 15 min , 30 min , 1 hour ....etc

取决于用户的选择。

当我启动我的应用程序时,我想获取我的当前时间,并且在每 n 个间隔之后我想执行异步任务

   int intv = 15;
   SimpleDateFormat sd = new SimpleDateFormat(
            "HH:mm:ss");
    Date date = new Date();
    sd.setTimeZone(TimeZone.getTimeZone("GMT+05:30"));
    System.out.println(sd.format(date));
    String currenttime = sd.format(date);
    Date myDateTime = null;
    try
      {
        myDateTime = sd.parse(currenttime);
      }
    catch (ParseException e)
      {
         e.printStackTrace();
      }
    System.out.println("This is the Actual        Date:"+sd.format(myDateTime));
    Calendar cal = new GregorianCalendar();
    cal.setTime(myDateTime);

            cal.add(Calendar.MINUTE , intv ); //here I am adding Interval
    System.out.println("This is Hours Added Date:"+sd.format(cal.getTime()));
    try {
        Date afterintv = sd.parse(sd.format(cal.getTime()));
        if(afterintv.after(myDateTime)){  //here i am comparing 
            System.out.println("true..........");
            new SendingTask().execute;  //this is the function i have to execute
        }
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

但我不知道该怎么做。

【问题讨论】:

    标签: android date calendar compare datetime-comparison


    【解决方案1】:

    如果您想在一段时间后运行 AsyncTask,您可以在 AsyncTask 中使用 Thread.sleep。在这种情况下是 SendingTask 类。这是一个示例:

    class SendingTask extends AsyncTask{
    
        // Interval is in milliseconds
        int interval = 1000;
    
        public SendingTask(int interval) {
            // Setting delay before anything is executed
            this.interval = interval;
        }
    
        @Override
        protected Object doInBackground(Object[] params) {
            // Wait according to interval
            try {
                Thread.sleep(interval);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }
    
        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            // update UI and restart asynctask
            textView3.setText("true..........");
            new SendingTask(3000).execute();
        }
    }
    

    【讨论】:

    • **是它实际上工作..因为我必须将输入作为用户的间隔,并且在每个相同的间隔之后我必须将数据发送到服务器**但我不明白你为什么第一次使用 1000和 3000 下一次,我的间隔是 15 分钟意味着 15*60*1000 所以我必须使用相同的间隔
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-03
    相关资源
    最近更新 更多