android 测试网速

该博客介绍了如何在Android中测量网络速度。通过下载指定大小的apk文件并计算下载时间,从而得出网络速度。代码示例中展示了使用HttpURLConnection进行网络请求,记录下载时间和大小,并在界面上显示速度结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原理: 到网上找个可以下载的apk 的URL,记住apk不要过大一般1M足够了.然后通过记录下载这个apk的时间和大小,算出当前网速.当然一个URL并不是很准确,要求精确的可以多下载几个
URL求平均值.

package com.panodic.settings.net;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import com.panodic.settings.util.LogUtil;
import com.panodic.settings.util.NetUtil;
import com.panodic.settings.util.Util;
import com.panodic.settings.view.PatchItem;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.panodic.settings.R;

public class MesureSpeed extends Activity implements OnClickListener {

	private static final int LOADING = 0x111;
	private static final int STOP = 0x112;
	private ProgressBar mBar;
	private int mProgressState;
	private TextView mSpeed;
	private Button mMeasureSpeed;
	private PatchItem mBack;
	private float mSpeedContent;
	private String mAddr = "http://cdn.market.hiapk.com/data/upload/2012/12_09/22/cn.lgx.phoneexpert_221804.apk";
	private String mAddr2 = "http://gdown.baidu.com/data/wisegame/6f9153d4a8d1f7d8/QQ.apk";
	private String mAddr3 = "http://gdown.baidu.com/data/wisegame/baidusearch_Android_10189_1399k.apk";
	private Handler mHandler = new Handler(Util.sTaskRunner.getLooper());
	private int testCount = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_mesure_speed);
		mSpeed = (TextView) findViewById(R.id.speed_content);
		mMeasureSpeed = (Button) findViewById(R.id.mesure_speed);
		mBack = (PatchItem) findViewById(R.id.patch_settings_net_speed);
		mBar = (ProgressBar) findViewById(R.id.bar);
		mMeasureSpeed.setOnClickListener(this);
		mBack.setOnClickListener(this);
		testCount = 0;
	}

	@Override
	public void onClick(View v) {
		if (mBack.isMyChild(v)) {
			Util.finish(this);
		} else if (v == mMeasureSpeed) {
			mMeasureSpeed.setEnabled(false);
			mBar.setVisibility(View.VISIBLE);
			mProgressState = 0;
			testCount = 0;
			mBar.setProgress(mProgressState);
			mHandler.removeCallbacks(null);
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					measureSpeed(mAddr);
				}
			}, 0);
		}
	}

	private Handler mProgressHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case LOADING:
				mBar.setProgress(mProgressState);
				break;
			case STOP:
				mBar.setVisibility(View.GONE);
				setSpeed();
				mMeasureSpeed.setEnabled(true);
				break;
			default:
				break;
			}
		}

	};

	private void setSpeed() {
		if (mSpeedContent >= 1024) {
			mSpeedContent = (float) ((mSpeedContent) / (1024 + 0.0));
			mSpeedContent = (float) (((int) (mSpeedContent * 10) % 10 + 0.0) / 10 + (int) mSpeedContent);
			mSpeed.setText(mSpeedContent + getString(R.string.m));
		} else {
			mSpeed.setText((int) mSpeedContent + getString(R.string.kb));
		}
	}

	private void measureSpeed(String httpUrl) {
		if (!NetUtil.isWifiConnected(this) && !NetUtil.isWireConnected(this)) {
			Toast.makeText(this, getString(R.string.no_net), Toast.LENGTH_SHORT)
					.show();
			mProgressHandler.sendEmptyMessage(STOP);
			return;
		}
		int fileLen = 0;
		long startTime = 0;
		long endTime = 0;
		final String fileName = "tmp.apk";
		HttpURLConnection conn = null;
		InputStream is = null;
		FileOutputStream fos = null;
		File tmpFile = new File("/sdcard/temp");
		if (!tmpFile.exists()) {
			tmpFile.mkdir();
		}
		final File file = new File("/sdcard/temp/" + fileName);
		try {
			URL url = new URL(httpUrl);
			try {
				conn = (HttpURLConnection) url.openConnection();
				LogUtil.d("lening");
				fileLen = conn.getContentLength();
				LogUtil.d("len=" + fileLen);
				if (fileLen <= 0) {
					mSpeedContent = 0;
					mProgressHandler.sendEmptyMessage(STOP);
					Toast.makeText(this, getString(R.string.conn_fail),
							Toast.LENGTH_SHORT).show();

					return;
				}
				startTime = System.currentTimeMillis();
				is = conn.getInputStream();
				fos = new FileOutputStream(file);
				byte[] buf = new byte[256];
				conn.connect();
				if (conn.getResponseCode() >= 400) {
					Toast.makeText(this, getString(R.string.no_time),
							Toast.LENGTH_SHORT).show();
					mProgressHandler.sendEmptyMessage(STOP);
					return;
				} else {
					while (true) {
						if (is != null) {
							int numRead = is.read(buf);
							if (numRead <= 0) {
								break;
							} else {
								fos.write(buf, 0, numRead);
							}
							mProgressState += (int) (((numRead + 0.0) / (fileLen + 0.0)) * 1000000);
							mProgressHandler.sendEmptyMessage(LOADING);
							// LogUtil.d("numRead=" + numRead + "  fileLen="
							// + fileLen);
						} else {
							break;
						}
					}
				}
				endTime = System.currentTimeMillis();
			} catch (IOException e) {
				e.printStackTrace();
				Toast.makeText(this, getString(R.string.no_permission),
						Toast.LENGTH_SHORT).show();
			} finally {
				if (conn != null) {
					conn.disconnect();
				}
				try {
					if (fos != null) {
						fos.close();
					}
					if (is != null) {
						is.close();
					}
				} catch (IOException e1) {
					e1.printStackTrace();
				}

			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		mSpeedContent = fileLen / (endTime - startTime);
		mProgressHandler.sendEmptyMessage(STOP);
	}
}


评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值