2016-03-26 67 views
0

我想每隔一段時間在Android中運行異步任務。比較連續兩次在android

我的間隔爲= {15分鐘,30分鐘,1小時....等

取決於用戶的選擇。

當我開始我的應用程序,然後我想取我的當前時間和每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(); 
    } 

但我沒有得到該怎麼辦了。

回答

0

如果您想在某段時間後運行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(); 
    } 
} 
+0

** _謝謝_ ** –

+0

不客氣,這是否回答你的問題? –

+0

**是它的工作其實..因爲我必須採取輸入作爲用戶的間隔,並在每隔相同的間隔後,我已經發送數據到服務器**,但我沒有得到爲什麼你第一次使用1000和下次3000,我的間隔是15分鐘意味着15 * 60 * 1000,所以我必須使用相同的時間間隔 –