Evening all, I got some way to do that...
First I have to create a class which extends BroadcasrReceiver, like this:
Manifest definition:
<receiver android:name=".core.CoreReceiver" android:enabled="true" android:exported="false">
<intent-filter>
<action android:name="android.net.ConnectivityManager.CONNECTIVITY_ACTION" />
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
Codes:
/**
* @author me
*/
public class CoreReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if (Constants.phone == null) {
// Receive [network] event
Constants.phone=new PhoneListen(context);
TelephonyManager telephony=(TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(Constants.phone, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
}
WifiManager wifi=(WifiManager)context.getSystemService(Context.WIFI_SERVICE);
boolean b=wifi.isWifiEnabled();
if (Constants.STATUS_WIFI != b) {
// WiFi status changed...
}
}
}
And a phone stats listener below...
public class PhoneListen extends PhoneStateListener {
private Context context;
public PhoneListen(Context c) {
context=c;
}
@Override
public void onDataConnectionStateChanged(int state) {
switch(state) {
case TelephonyManager.DATA_DISCONNECTED:// 3G
//3G has been turned OFF
break;
case TelephonyManager.DATA_CONNECTING:// 3G
//3G is connecting
break;
case TelephonyManager.DATA_CONNECTED:// 3G
//3G has turned ON
break;
}
}
}
Finally, here's my logic
- Collect count into SQLite DB.
- Collect all app network usage via TrafficStats every 1 minute, only when 3G is ON.
- If 3G is OFF, then stop collecting.
- If both 3G & WiFi are ON, stop collecting.
As I know, network traffic will go through WiFi only, if both 3G & WiFi are available.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…