流量监听

监听流量,保存到本地,合适的时间发送到服务器

对于Android流量统计来说在2.2版中新加入了TrafficStats类可以轻松获取,其实本身TrafficStats类也是读取Linux提供的文件对象系统类型的文本进行解析。android.net.TrafficStats类中,提供了多种静态方法,可以直接调用获取,返回类型均为 long型,如果返回等于-1代表 UNSUPPORTED 当前设备不支持统计。 

Java代码  

 
static long  getMobileRxBytes()  //获取通过Mobile连接收到的字节总数,不包含WiFi  
static long  getMobileRxPackets()  //获取Mobile连接收到的数据包总数  
static long  getMobileTxBytes()  //Mobile发送的总字节数  
static long  getMobileTxPackets()  //Mobile发送的总数据包数  
static long  getTotalRxBytes()  //获取总的接受字节数,包含Mobile和WiFi等  
static long  getTotalRxPackets()  //总的接受数据包数,包含Mobile和WiFi等  
static long  getTotalTxBytes()  //总的发送字节数,包含Mobile和WiFi等  
static long  getTotalTxPackets()  //发送的总数据包数,包含Mobile和WiFi等   
static long  getUidRxBytes(int uid)  //获取某个网络UID的接受字节数  
static long  getUidTxBytes(int uid) //获取某个网络UID的发送字节数   

下面是业务逻辑:

Service:

package com.example.app;

import java.util.Calendar;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.TrafficStats;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service implements Runnable {
     private static long interval = 1000*60*60*1;//间隔时间,,每隔一段时间记录一次3g/2g产生的流量,默认是1小时
    private long sleepTime = (long) (1000 *60 *0.1);//停留的时间
    
    private static int hour = 18;//发送流量到服务器的时间--小时
    private static int minute = 30;//发送流量到服务器的时间--分钟
    public static boolean isrun = false;
    private long lastTime = 0;//上一次保存流量的时间
    Context con;
    
    
    public MyService() {

    }

    /**
     * @param interval
     *            间隔时间,,每隔一段时间记录一次3g/2g产生的流量,默认是1小时
     */
    public MyService(long interval) {
        this.interval = interval;
    }
    
    /**
     * 
     * @param interval  间隔时间,,每隔一段时间记录一次3g/2g产生的流量,默认是1小时
     * @param hour 发送流量到服务器的时间--小时  默认是18
     * @param minute 发送流量到服务器的时间--分钟 默认是30
     */
    public MyService(long interval,int hour,int minute){
        this.interval = interval;
        this.hour = hour;
        this.minute = minute;
        
    }
    
    /**
     * 
     * @param interval  间隔时间,,每隔一段时间记录一次3g/2g产生的流量,默认是1小时
     * @param hour 发送流量到服务器的时间--小时  默认是18
     * @param minute 发送流量到服务器的时间--分钟 默认是30
     */
    public static void init(long interval,int hour,int minute){
        MyService.interval = interval;
        MyService.hour = hour;
        MyService.minute = minute;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        while (isrun) {
            // 每隔一段时间保持当前流量值
            long nowtime = System.currentTimeMillis();
            if (nowtime - lastTime >= interval) {
                lastTime = nowtime;
                long i1 = TrafficStats.getMobileRxBytes();
                long total = Storage.getLong(con, Storage.TotalMobileRxBytes);
                long last = Storage.getLong(con, Storage.LastMobileRxBytes);

                long now = total + i1 - last;
                Storage.saveLong(con, Storage.TotalMobileRxBytes, now);
                Storage.saveLong(con, Storage.LastMobileRxBytes, i1);
                // Toast.makeText(con, now+"", 0).show();
                Log.i("之前总流量", total + "");
                Log.i("获取流量", i1 + "");
                Log.i("上次流量", last + "");
                Log.i("当前总流量", now + "");

            } else {
                try {
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }

    }

    /**
     * 每天定时发送流量到服务器
     */
    Thread sendThread = new Thread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (isrun) {
                Calendar c = Calendar.getInstance();
                int hour1 = c.get(Calendar.HOUR_OF_DAY);
                int minute1 = c.get(Calendar.MINUTE);

                if (hour1 == hour && minute == minute1 ) {
                    sendToService();
                }else if(!Storage.getBlooean(con, Storage.hasSend) 
                        &&(hour<hour1 ||( hour == hour1 && minute<minute1)) ){
                    sendToService();
                    
                }
            }
        }

        private void sendToService() {
            System.out.println("开始上传流量到服务器");
            Storage.saveLong(con, Storage.TotalMobileRxBytes, (long) 0);
            Storage.saveBoolean(con, Storage.hasSend, true);
            
            try {
                Thread.sleep(1000*60*2);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

    
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("MyService--", "onStartCommand");
        con = this;
        isrun = true;
        lastTime = System.currentTimeMillis();
        Thread t = new Thread(this);
        if(!t.isAlive())
            t.start();
        if(!sendThread.isAlive())
            sendThread.start();
        return startId;
        
        
    };
    
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        Log.i("MyService--", "onCreate");
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        Log.i("MyService--", "onDestroy");
        isrun = false;
        stopSelf();
        System.out.println("停止监听12222222");

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

}

Storage里是SharedPreferences的一些操作,我下一篇随笔会写出来。

现在就是自己写个demo,打开服务,对保存的流量做一些处理就ok了。

原文地址:https://www.cnblogs.com/yuanyuan-5683/p/trafficstats.html