您可以为WiFi和移动网络注册BroadcastReceiver,然后将时间保存在BroadcastReceiver类的onReceive()方法中
public class NetworkReceiver extends BroadcastReceiver {
private final String TAG = "WifiReceiver";
public static final String WIFI_DISCONNECTED_TIME = "wifi_disconnected_time";
public static final String WIFI_CONNECTED_TIME = "wifi_connected_time";
@Override
public void onReceive(Context context, Intent intent) {
MyLog.e(TAG, "Broadcast");
if(intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
NetworkInfo netInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
String networkStateText;
switch (netInfo.getState()) {
case DISCONNECTING:
networkStateText = "DISCONNECTING";
break;
case DISCONNECTED:
networkStateText = "DISCONNECTED";
//Save the time internet disconnected here
context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE).edit().putLong(WIFI_DISCONNECTED_TIME, System.currentTimeMillis()).commit();
break;
case CONNECTING:
networkStateText = "CONNECTING";
break;
case CONNECTED:
networkStateText = "CONNECTED";
//Save the time internet connected here
context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE).edit().putLong(WIFI_CONNECTED_TIME, System.currentTimeMillis()).commit();
break;
case SUSPENDED:
networkStateText = "SUSPENDED";
break;
case UNKNOWN:
networkStateText = "UNKNOWN";
break;
default:
networkStateText = "No State";
break;
}
MyLog.e(TAG, "Broadcast > NetworkState: " + networkStateText);
}
}
}
不要忘记放入权限android.permission.ACCESS_NETWORK_STATE并将接收器添加到android清单。
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
然后你可以在Activity课程中从SharedPreferences获得时间。
祝好运。