我正在手机中实现一项功能。
我想在状态栏上显示动态数据使用情况。
我该怎么做?
答案 0 :(得分:1)
使用以下代码实现工具栏上的数据使用。如果要在状态栏上实现,则需要通过窗口管理器实现它。没有直接api与状态栏交谈
private long total_rcv;
private long total_send;
private long prev_upload_speed;
private long prev_download_speed;
private Handler mHandler;
private TextView networkSpeedMeter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
networkSpeedMeter = (TextView) toolbar.findViewById(R.id.networkspeed);
mHandler = new Handler();
if(mHandler!=null){
mHandler.removeCallbacks(runnable);
mHandler.post(runnable);
}
}
protected void onDestroy() {
if(mHandler!=null){
mHandler.removeCallbacks(runnable);
mHandler=null;
}
super.onDestroy();
};
private Runnable runnable = new Runnable() {
@Override
public void run() {
//do the job
final long download_speed = (TrafficStats.getTotalRxBytes()-total_rcv)/1024;
final long upload_speed = (TrafficStats.getTotalTxBytes()-total_send)/1024;
if(networkSpeedMeter!=null && (prev_download_speed!= download_speed || prev_upload_speed != upload_speed) ){
prev_download_speed = download_speed;
prev_upload_speed = upload_speed;
networkSpeedMeter.setText( String.format("D:%4sKB/S%4sU:%4sKB/S", download_speed, "", upload_speed) );
}
total_rcv = TrafficStats.getTotalRxBytes();
total_send = TrafficStats.getTotalTxBytes();
if(mHandler!=null){
mHandler.postDelayed(this,1000L*1); /*every 1 second*/
}
}
};