2012-03-12 131 views
0

所以我寫了一些代碼,以節省在無線網絡上花費的時間。除了時間沒有正確保存,我幾乎在那裏。日曆問題,不保存日期

該對象接收廣播,之後檢查它是否連接到wifi AP。它在連接的時刻獲取Date對象。斷開連接後,獲取連接中斷的日期。

然而,當它記錄的開始和結束日期似乎總是得到當前的日期,也爲起始對象:

private Date startDate; 
private Date stopDate; 
@Override 
public void onReceive(Context context, Intent intent) { 
    if (isOnline(context)) { 
     WifiManager wifiManager = (WifiManager) context 
       .getSystemService(Context.WIFI_SERVICE); 
     android.net.wifi.WifiInfo wifiInfo = wifiManager 
       .getConnectionInfo(); 
     Log.d("WIFI:", "IN FIRST IF, SO CONNECTED"); 
     if (wifiInfo.getSupplicantState() == (SupplicantState.COMPLETED)) { 
      Calendar c = Calendar.getInstance(); 
      this.startDate = c.getTime(); 
      this.initialConnection = true; 
     } 
    } else if (this.initialConnection) { 
     Calendar d = Calendar.getInstance(); 
     this.stopDate = d.getTime(); 
     //problem persists here 
     String s = "TIME:" + d.getTime().toString() + " started at:" 
       + startDate.toString() + "stopped at" 
       + this.stopDate.toString(); 
     Log.d("WIFI:", s); 
     this.initialConnection = false; 
    } 
} 

輸出

D/WIFI: ( 684): TIME:Mon Mar 12 13:18:16 GMT+02:00 2012 started at:Mon Mar 12 13:18:16 GMT+02:00 2012stopped atMon Mar 12 13:18:16 GMT+02:00 2012 

是我的開始時間獲取當前時間再次提到它時?我怎樣才能讓它保存startTime?

回答

0

我無法找到使用日曆的任何錯誤。以下SSCCE具有正確的行爲。 onReceive()中的邏輯必定存在問題。也許上半場被再次調用導致startDate被更新到當前時間。

public class CalendarTest { 
    private Date stopDate; 
    private Date startDate; 

    public void online() { 
     Calendar c = Calendar.getInstance(); 
     this.startDate = c.getTime(); 
    } 

    public void offline() { 
     Calendar d = Calendar.getInstance(); 
     this.stopDate = d.getTime(); 
     String s = "TIME:" + d.getTime().toString() + "\nstarted at:" 
       + startDate.toString() + "\nstopped at" 
       + this.stopDate.toString(); 
     System.out.println(s); 
    } 

    public static void main(String[] args) { 
     CalendarTest test = new CalendarTest(); 
     test.online(); 
     try { 
      Thread.sleep(3000); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
     test.offline(); 
    } 
} 

輸出

TIME:Mon Mar 12 12:29:04 GMT 2012 
started at:Mon Mar 12 12:29:01 GMT 2012 
stopped atMon Mar 12 12:29:04 GMT 2012