所以我写了一些代码来节省在wifi网络上花费的时间。我几乎在那里,除了时间没有得到正确保存。
此对象接收广播,然后检查它是否连接到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在被引用时是否再次获得当前时间?如何保存startTime?
答案 0 :(得分: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