开发者

Data usage on Android

I want to开发者_如何学Go find the start time and end time of the Internet usage in Android? How can I find it? What package do I need to use for that?


Saran,

You'll want to use the TrafficStats class.


You can register a BroadcastReceiver for WiFi and Mobile Network, then save the time in onReceive() method of the BroadcastReceiver class

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);
        }
    }
}

Don't forget to put permission android.permission.ACCESS_NETWORK_STATE and add the receiver to android manifest.

    <!-- Check for Internet Connectivity -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <receiver android:name=".NetworkReceiver" >
            <intent-filter>
                <action android:name="android.net.wifi.STATE_CHANGE" />
            </intent-filter>
        </receiver>
    </application>

Then you can get the time from your SharedPreferences in your Activity class.

Good Luck.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜