Android网络下载速度测试

Java代码   收藏代码
  1. 开发工具:  
  2. 1. EC   
  3. 2. SDK 1.1   
  4. 3. ADT 0.8  
 
Java代码   收藏代码
  1. 原理:通过下载文件的大小,和当前读取的字节数,在固定的时间中检测速度,详细请看代码,  
  2. 我这里使用可一张图片做的测试:http://www.straitstimes.com/STI/STIMEDIA/image/20090324/BUSKING.jpg  

 NetWorkSpeedInfo.java Android NetWork info

 

Java代码   收藏代码
  1. package cc.androidos.speed;  
  2.   
  3.   
  4. /** 
  5.  * A class for android network info  
  6.  * @author Wang Baoxi 
  7.  * @version 1.0 
  8.  * @since 2009-5-27 
  9.  */  
  10. public class NetWorkSpeedInfo  
  11. {  
  12.       
  13.     /**Network speed*/  
  14.     public  long speed = 0;  
  15.     /**Had finished bytes*/  
  16.     public  long hadFinishedBytes = 0;  
  17.     /**Total bytes of a file, default is 1024 bytes,1K*/  
  18.     public  long totalBytes = 1024;  
  19.       
  20.     /**The net work type, 3G or GSM and so on*/  
  21.     public  int networkType = 0;  
  22.       
  23.     /**Down load the file percent 0----100*/  
  24.     public  int downloadPercent = 0;  
  25. }  

 SpeedActivity.java Activity

 

Java代码   收藏代码
  1. package cc.androidos.speed;  
  2.   
  3.   
  4. import android.app.Activity;  
  5. import android.graphics.Bitmap;  
  6. import android.graphics.BitmapFactory;  
  7. import android.os.Bundle;  
  8. import android.os.Handler;  
  9. import android.os.Message;  
  10. import android.util.Log;  
  11. import android.view.View;  
  12. import android.widget.Button;  
  13. import android.widget.ImageView;  
  14. import android.widget.TextView;  
  15.   
  16.   
  17. /** 
  18.  *  
  19.  * @author Wang Baoxi 
  20.  * @version 1.0 
  21.  * @since 2009-5-27 
  22.  */  
  23. public class SpeedActivity extends Activity  
  24. {  
  25.     /** Called when the activity is first created. */  
  26.   
  27.     TextView fileLength = null;  
  28.     TextView speed = null;  
  29.     TextView hasDown = null;  
  30.     TextView percent = null;  
  31.     String url = "";  
  32.   
  33.     ImageView imageView = null;  
  34.     byte[] imageData = null;  
  35.   
  36.     NetWorkSpeedInfo netWorkSpeedInfo = null;  
  37.     private final int UPDATE_SPEED = 1;  
  38.     @Override  
  39.     public void onCreate( Bundle savedInstanceState )  
  40.     {  
  41.         super.onCreate( savedInstanceState );  
  42.         setContentView( R.layout.main );  
  43.   
  44.         hasDown = ( TextView ) findViewById( R.id.hasDown );  
  45.         fileLength = ( TextView ) findViewById( R.id.fileLength );  
  46.         speed = ( TextView ) findViewById( R.id.speed );  
  47.         percent = ( TextView ) findViewById( R.id.percent );  
  48.         imageView = ( ImageView ) findViewById( R.id.ImageView01 );  
  49.         Button b = ( Button ) findViewById( R.id.Button01 );  
  50.         url = getString( R.string.image_url );  
  51.         netWorkSpeedInfo = new NetWorkSpeedInfo();  
  52.         b.setOnClickListener( new View.OnClickListener()  
  53.         {  
  54.             @Override  
  55.             public void onClick( View arg0 )  
  56.             {  
  57.   
  58.                 //down load the file thread  
  59.                 new Thread()  
  60.                 {  
  61.                     @Override  
  62.                     public void run()  
  63.                     {  
  64.                         imageData = ReadFile.getFileFromUrl( url,  
  65.                             netWorkSpeedInfo );  
  66.                         stop();  
  67.                     }  
  68.                 }.start();  
  69.   
  70.                 //get the speed , down load bytes ,update the view thread  
  71.                 new Thread()  
  72.                 {  
  73.                     @Override  
  74.                     public void run()  
  75.                     {  
  76.   
  77.                         while ( netWorkSpeedInfo.hadFinishedBytes < netWorkSpeedInfo.totalBytes )  
  78.                         {  
  79.                             netWorkSpeedInfo.downloadPercent = ( int ) (( ( double ) netWorkSpeedInfo.hadFinishedBytes /   
  80.                                     ( double ) netWorkSpeedInfo.totalBytes ) * 100);  
  81.                             try  
  82.                             {  
  83.                                 sleep( 1500 );  
  84.                             }  
  85.                             catch ( InterruptedException e )  
  86.                             {  
  87.                                 e.printStackTrace();  
  88.                             }  
  89.   
  90.                             Log.e( "update,send the message to update""" );  
  91.                             //update view  
  92.                             handler.sendEmptyMessage( UPDATE_SPEED );  
  93.                         }  
  94.                           
  95.                         //finished  
  96.                         if( netWorkSpeedInfo.hadFinishedBytes == netWorkSpeedInfo.totalBytes )  
  97.                         {  
  98.   
  99.                             netWorkSpeedInfo.downloadPercent = ( int ) (( ( double ) netWorkSpeedInfo.hadFinishedBytes /  
  100.                                     ( double ) netWorkSpeedInfo.totalBytes ) * 100);  
  101.                             handler.sendEmptyMessage( UPDATE_SPEED );  
  102.                             Log.e( "update",  
  103.                                 ",send the message to update and stop" );  
  104.                             stop();  
  105.                         }  
  106.   
  107.                     }  
  108.                 }.start();  
  109.             }  
  110.         } );  
  111.     }  
  112.   
  113.     
  114.       
  115.     /** 
  116.      * Handler for post message into OS 
  117.      */  
  118.     private Handler handler = new Handler()  
  119.     {  
  120.         @Override  
  121.         public void handleMessage( Message msg )  
  122.         {  
  123.             int value = msg.what;  
  124.             switch ( value )  
  125.             {  
  126.                 case UPDATE_SPEED:  
  127.                     updateView();  
  128.                     break;  
  129.                 default:  
  130.                     break;  
  131.             }  
  132.         }  
  133.     };  
  134.   
  135.     /** 
  136.      * Update the view method 
  137.      */  
  138.     private void updateView()  
  139.     {  
  140.         speed.setText( netWorkSpeedInfo.speed + "bytes/s" );  
  141.         hasDown.setText( netWorkSpeedInfo.hadFinishedBytes + "bytes" );  
  142.         fileLength.setText( netWorkSpeedInfo.totalBytes + "" );  
  143.   
  144.         percent.setText( netWorkSpeedInfo.downloadPercent+"%" );  
  145.   
  146.         if( imageData != null )  
  147.         {  
  148.             Bitmap b = BitmapFactory.decodeByteArray( imageData, 0,  
  149.                 imageData.length );  
  150.             imageView.setImageBitmap( b );  
  151.         }  
  152.     }  
  153. }  

 ReadFile.java Read file from web

Java代码   收藏代码
  1. package cc.androidos.speed;  
  2.   
  3. import java.io.InputStream;  
  4. import java.net.URL;  
  5. import java.net.URLConnection;  
  6.   
  7. import android.util.Log;  
  8. /** 
  9.  *  
  10.  * @author Wang Baoxi 
  11.  * @version 1.0 
  12.  * @since 2009-5-27 
  13.  */  
  14. public class ReadFile  
  15. {  
  16.   
  17.     /** 
  18.      * <p> 
  19.      * Read file from web 
  20.      * </p> 
  21.      * @param url 
  22.      * @param netWorkSpeedInfo 
  23.      * @return 
  24.      */  
  25.     public static byte[] getFileFromUrl( String url,NetWorkSpeedInfo netWorkSpeedInfo )  
  26.     {  
  27.         int currentByte = 0;  
  28.         int fileLength = 0;  
  29.         long startTime = 0;  
  30.         long intervalTime = 0;  
  31.   
  32.         byte[] b = null;  
  33.           
  34.         int bytecount = 0;  
  35.         URL urlx = null;  
  36.         URLConnection con = null;  
  37.         InputStream stream = null;  
  38.         try  
  39.         {  
  40.             Log.d( "URL:", url );  
  41.             urlx = new URL( url );  
  42.             con = urlx.openConnection();  
  43.             con.setConnectTimeout( 20000 );  
  44.             con.setReadTimeout( 20000 );  
  45.             fileLength = con.getContentLength();  
  46.             stream = con.getInputStream();  
  47.             netWorkSpeedInfo.totalBytes = fileLength;  
  48.             b = new byte[fileLength];  
  49.             startTime = System.currentTimeMillis();  
  50.             while ( ( currentByte = stream.read() ) != -1 )  
  51.             {  
  52.                 netWorkSpeedInfo.hadFinishedBytes++;  
  53.                 intervalTime = System.currentTimeMillis() - startTime;  
  54.                 if(intervalTime==0){  
  55.                     netWorkSpeedInfo.speed = 1000;  
  56.                 }else{  
  57.                     netWorkSpeedInfo.speed = (  netWorkSpeedInfo.hadFinishedBytes / intervalTime ) * 1000;  
  58.                 }  
  59.                 if(bytecount<fileLength){  
  60.                     b[bytecount++] = ( byte ) currentByte;  
  61.                 }  
  62.             }  
  63.         }  
  64.         catch ( Exception e )  
  65.         {  
  66.             Log.e( "exception : ", e.getMessage()+"" );  
  67.         }  
  68.         finally  
  69.         {  
  70.             try  
  71.             {  
  72.                 if( stream != null )  
  73.                 {  
  74.                     stream.close();  
  75.                 }  
  76.             }  
  77.             catch ( Exception e )  
  78.             {  
  79.                 Log.e( "exception : ", e.getMessage() );  
  80.             }  
  81.   
  82.         }  
  83.         return b;  
  84.     }  
  85.   
  86. }  
 


 

以上内容Sinfransis版权所有,专注请注明来自  http://mdev.cc/dev

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Retrofit进行网络请求,并使用OkHttp拦截器来实现上传和下载速率的测量。以下是一个示例: 首先,添加依赖: ```groovy implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0' implementation 'com.squareup.okhttp3:logging-interceptor:4.9.1' ``` 然后,创建一个Retrofit实例: ```java OkHttpClient.Builder httpClient = new OkHttpClient.Builder() .addInterceptor(new Interceptor() { @Override public okhttp3.Response intercept(Chain chain) throws IOException { Request original = chain.request(); Request.Builder requestBuilder = original.newBuilder() .method(original.method(), original.body()); Request request = requestBuilder.build(); return chain.proceed(request); } }) .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)); Retrofit retrofit = new Retrofit.Builder() .baseUrl("YOUR_BASE_URL") .client(httpClient.build()) .addConverterFactory(GsonConverterFactory.create()) .build(); ``` 接下来,创建一个API接口: ```java public interface ApiService { @Multipart @POST("YOUR_ENDPOINT") Call<ResponseBody> uploadFile(@Part MultipartBody.Part file); } ``` 最后,执行网络请求并测量上传速度: ```java File file = new File("YOUR_FILE_PATH"); RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file); MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), requestBody); ApiService service = retrofit.create(ApiService.class); Call<ResponseBody> call = service.uploadFile(filePart); long startTime = System.currentTimeMillis(); call.execute(); long endTime = System.currentTimeMillis(); long duration = endTime - startTime; long fileSize = file.length(); double speed = (double) fileSize / duration; Log.d("UPLOAD_SPEED", "Speed: " + speed + " bytes/ms"); ``` 注意:这只是一个简单的示例代码,你可能需要根据你的具体情况进行适当的调整。此外,测量下载速度的方法与上传速度的方法类似。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值