您的位置:首页 > 理论基础 > 计算机网络

Android网络下载速度测试

2015-01-14 16:29 246 查看
Java代码  


开发工具:  

1. EC   

2. SDK 1.1   

3. ADT 0.8  

 

Java代码  


原理:通过下载文件的大小,和当前读取的字节数,在固定的时间中检测速度,详细请看代码,  

我这里使用可一张图片做的测试:http://www.straitstimes.com/STI/STIMEDIA/image/20090324/BUSKING.jpg  

 NetWorkSpeedInfo.java Android NetWork info

 

Java代码  


package cc.androidos.speed;  

  

  

/** 

 * A class for android network info  

 * @author Wang Baoxi 

 * @version 1.0 

 * @since 2009-5-27 

 */  

public class NetWorkSpeedInfo  

{  

      

    /**Network speed*/  

    public  long speed = 0;  

    /**Had finished bytes*/  

    public  long hadFinishedBytes = 0;  

    /**Total bytes of a file, default is 1024 bytes,1K*/  

    public  long totalBytes = 1024;  

      

    /**The net work type, 3G or GSM and so on*/  

    public  int networkType = 0;  

      

    /**Down load the file percent 0----100*/  

    public  int downloadPercent = 0;  

}  

 SpeedActivity.java Activity

 

Java代码  


package cc.androidos.speed;  

  

  

import android.app.Activity;  

import android.graphics.Bitmap;  

import android.graphics.BitmapFactory;  

import android.os.Bundle;  

import android.os.Handler;  

import android.os.Message;  

import android.util.Log;  

import android.view.View;  

import android.widget.Button;  

import android.widget.ImageView;  

import android.widget.TextView;  

  

  

/** 

 *  

 * @author Wang Baoxi 

 * @version 1.0 

 * @since 2009-5-27 

 */  

public class SpeedActivity extends Activity  

{  

    /** Called when the activity is first created. */  

  

    TextView fileLength = null;  

    TextView speed = null;  

    TextView hasDown = null;  

    TextView percent = null;  

    String url = "";  

  

    ImageView imageView = null;  

    byte[] imageData = null;  

  

    NetWorkSpeedInfo netWorkSpeedInfo = null;  

    private final int UPDATE_SPEED = 1;  

    @Override  

    public void onCreate( Bundle savedInstanceState )  

    {  

        super.onCreate( savedInstanceState );  

        setContentView( R.layout.main );  

  

        hasDown = ( TextView ) findViewById( R.id.hasDown );  

        fileLength = ( TextView ) findViewById( R.id.fileLength );  

        speed = ( TextView ) findViewById( R.id.speed );  

        percent = ( TextView ) findViewById( R.id.percent );  

        imageView = ( ImageView ) findViewById( R.id.ImageView01 );  

        Button b = ( Button ) findViewById( R.id.Button01 );  

        url = getString( R.string.image_url );  

        netWorkSpeedInfo = new NetWorkSpeedInfo();  

        b.setOnClickListener( new View.OnClickListener()  

        {  

            @Override  

            public void onClick( View arg0 )  

            {  

  

                //down load the file thread  

                new Thread()  

                {  

                    @Override  

                    public void run()  

                    {  

                        imageData = ReadFile.getFileFromUrl( url,  

                            netWorkSpeedInfo );  

                        stop();  

                    }  

                }.start();  

  

                //get the speed , down load bytes ,update the view thread  

                new Thread()  

                {  

                    @Override  

                    public void run()  

                    {  

  

                        while ( netWorkSpeedInfo.hadFinishedBytes < netWorkSpeedInfo.totalBytes )  

                        {  

                            netWorkSpeedInfo.downloadPercent = ( int ) (( ( double ) netWorkSpeedInfo.hadFinishedBytes /   

                                    ( double ) netWorkSpeedInfo.totalBytes ) * 100);  

                            try  

                            {  

                                sleep( 1500 );  

                            }  

                            catch ( InterruptedException e )  

                            {  

                                e.printStackTrace();  

                            }  

  

                            Log.e( "update,send the message to update", "" );  

                            //update view  

                            handler.sendEmptyMessage( UPDATE_SPEED );  

                        }  

                          

                        //finished  

                        if( netWorkSpeedInfo.hadFinishedBytes == netWorkSpeedInfo.totalBytes )  

                        {  

  

                            netWorkSpeedInfo.downloadPercent = ( int ) (( ( double ) netWorkSpeedInfo.hadFinishedBytes /  

                                    ( double ) netWorkSpeedInfo.totalBytes ) * 100);  

                            handler.sendEmptyMessage( UPDATE_SPEED );  

                            Log.e( "update",  

                                ",send the message to update and stop" );  

                            stop();  

                        }  

  

                    }  

                }.start();  

            }  

        } );  

    }  

  

    

      

    /** 

     * Handler for post message into OS 

     */  

    private Handler handler = new Handler()  

    {  

        @Override  

        public void handleMessage( Message msg )  

        {  

            int value = msg.what;  

            switch ( value )  

            {  

                case UPDATE_SPEED:  

                    updateView();  

                    break;  

                default:  

                    break;  

            }  

        }  

    };  

  

    /** 

     * Update the view method 

     */  

    private void updateView()  

    {  

        speed.setText( netWorkSpeedInfo.speed + "bytes/s" );  

        hasDown.setText( netWorkSpeedInfo.hadFinishedBytes + "bytes" );  

        fileLength.setText( netWorkSpeedInfo.totalBytes + "" );  

  

        percent.setText( netWorkSpeedInfo.downloadPercent+"%" );  

  

        if( imageData != null )  

        {  

            Bitmap b = BitmapFactory.decodeByteArray( imageData, 0,  

                imageData.length );  

            imageView.setImageBitmap( b );  

        }  

    }  

}  

 ReadFile.java Read file from web

Java代码  


package cc.androidos.speed;  

  

import java.io.InputStream;  

import java.net.URL;  

import java.net.URLConnection;  

  

import android.util.Log;  

/** 

 *  

 * @author Wang Baoxi 

 * @version 1.0 

 * @since 2009-5-27 

 */  

public class ReadFile  

{  

  

    /** 

     * <p> 

     * Read file from web 

     * </p> 

     * @param url 

     * @param netWorkSpeedInfo 

     * @return 

     */  

    public static byte[] getFileFromUrl( String url,NetWorkSpeedInfo netWorkSpeedInfo )  

    {  

        int currentByte = 0;  

        int fileLength = 0;  

        long startTime = 0;  

        long intervalTime = 0;  

  

        byte[] b = null;  

          

        int bytecount = 0;  

        URL urlx = null;  

        URLConnection con = null;  

        InputStream stream = null;  

        try  

        {  

            Log.d( "URL:", url );  

            urlx = new URL( url );  

            con = urlx.openConnection();  

            con.setConnectTimeout( 20000 );  

            con.setReadTimeout( 20000 );  

            fileLength = con.getContentLength();  

            stream = con.getInputStream();  

            netWorkSpeedInfo.totalBytes = fileLength;  

            b = new byte[fileLength];  

            startTime = System.currentTimeMillis();  

            while ( ( currentByte = stream.read() ) != -1 )  

            {  

                netWorkSpeedInfo.hadFinishedBytes++;  

                intervalTime = System.currentTimeMillis() - startTime;  

                if(intervalTime==0){  

                    netWorkSpeedInfo.speed = 1000;  

                }else{  

                    netWorkSpeedInfo.speed = (  netWorkSpeedInfo.hadFinishedBytes / intervalTime ) * 1000;  

                }  

                if(bytecount<fileLength){  

                    b[bytecount++] = ( byte ) currentByte;  

                }  

            }  

        }  

        catch ( Exception e )  

        {  

            Log.e( "exception : ", e.getMessage()+"" );  

        }  

        finally  

        {  

            try  

            {  

                if( stream != null )  

                {  

                    stream.close();  

                }  

            }  

            catch ( Exception e )  

            {  

                Log.e( "exception : ", e.getMessage() );  

            }  

  

        }  

        return b;  

    }  

  

}  

 



 

以上内容Sinfransis版权所有,专注请注明来自  http://mdev.cc/dev
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: