Android实时获取当前下载速度

第一步

public class Net_Service extends Service {

    private long total_data = TrafficStats.getTotalRxBytes();
    private Handler mHandler;
    //几秒刷新一次
    private final int count = 5;



    /**
     * 定义线程周期性地获取网速
     */
    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            //定时器
            mHandler.postDelayed(mRunnable, count * 1000);
            Message msg = mHandler.obtainMessage();
            msg.what = 1;
            msg.arg1 = getNetSpeed();
            mHandler.sendMessage(msg);
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();

        mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 1) {
                    //float real_data = (float)msg.arg1;
                    if(msg.arg1  > 1024 ){
                        //System.out.println(msg.arg1 / 1024 + "kb/s");
                        Intent intent  = new Intent();
                        intent.setAction("com.weilian.fmscms.speed");
                        intent.putExtra("speed",msg.arg1 / 1024 + "kb/s");
                        sendBroadcast(intent);
                    }
                    else{
                        //System.out.println(msg.arg1 + "b/s");
                    }
                }
            }
        };



    }

    /**
     * 核心方法,得到当前网速
     * @return
     */
    private int getNetSpeed() {
        long traffic_data = TrafficStats.getTotalRxBytes() - total_data;
        total_data = TrafficStats.getTotalRxBytes();
        return (int)traffic_data /count ;
    }

    /**
     * 启动服务时就开始启动线程获取网速
     */
    @Override
    public void onStart(Intent intent, int startId) {
        mHandler.postDelayed(mRunnable, 0);
    };

    /**
     * 在服务结束时删除消息队列
     */
    @Override
    public void onDestroy() {
        mHandler.removeCallbacks(mRunnable);
        super.onDestroy();
    };

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }



}


第二步

**

第三步

//实时监听网路变化情况
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.weilian.fmscms.speed");
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                mTvSpeed.setText(intent.getStringExtra("speed"));
            }
        };
        registerReceiver(broadcastReceiver,intentFilter);

        startService(new Intent(ShowActivity.this,Net_Service.class));

参考自:http://www.mamicode.com/info-detail-225320.html

你可能感兴趣的:(android,android)