Androidは現在のダウンロード速度をリアルタイムで取得
5674 ワード
最初のステップ
ステップ2
**
ステップ3
参照先:http://www.mamicode.com/info-detail-225320.html
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;
}
}
ステップ2
**
ステップ3
//
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