我正在创建一个跟踪所用字节数的应用程序。我希望在total_bytes达到某个值(例如1000字节)时收到通知。我在互联网上搜索了大约一个小时,我还没有找到任何有用的东西。我该怎么做呢?
public class Data_usage extends AppCompatActivity {
private Handler mHandler = new Handler();
private long mStartRX = 0;
private long mStartTX = 0;
long total_bytes;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_usage);
if (mStartRX == TrafficStats.UNSUPPORTED || mStartTX == TrafficStats.UNSUPPORTED) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Uh Oh!");
alert.setMessage("Your device does not support traffic stat monitoring.");
alert.show();
}
else
{
mHandler.postDelayed(mRunnable, 1000);
}
}
public final Runnable mRunnable=new Runnable() {
@Override
public void run() {
TextView RX = (TextView)findViewById(R.id.RX);
TextView TX = (TextView)findViewById(R.id.TX);
TextView Totalbytes=(TextView)findViewById(R.id.TOTALX);
final long rxBytes=TrafficStats.getMobileRxBytes()-mStartRX;
RX.setText(Long.toString(rxBytes));
final long txBytes=TrafficStats.getMobileTxBytes()-mStartTX;
TX.setText(Long.toString(txBytes));
Totalbytes.setText(Long.toString(total_bytes));
long Txx=rxBytes;
long Rxx=txBytes;
total_bytes=Rxx+Txx;
mHandler.postDelayed(mRunnable, 1000);
}
};
}
答案 0 :(得分:0)
可能有第二个活动即通知。
public final Runnable mRunnable=new Runnable() {
@Override
public void run() {
TextView RX = (TextView)findViewById(R.id.RX);
TextView TX = (TextView)findViewById(R.id.TX);
TextView Totalbytes=(TextView)findViewById(R.id.TOTALX);
final long rxBytes=TrafficStats.getMobileRxBytes()-mStartRX;
RX.setText(Long.toString(rxBytes));
final long txBytes=TrafficStats.getMobileTxBytes()-mStartTX;
TX.setText(Long.toString(txBytes));
Totalbytes.setText(Long.toString(total_bytes));
long Txx=rxBytes;
long Rxx=txBytes;
total_bytes=Rxx+Txx;
Intent myIntent = new Intent(this, Notification.Class);
Bundle bundle = myIntent.getExtras();
bundle.putInt("bytes", total_bytes);
startActivity(myIntent);
mHandler.postDelayed(mRunnable, 1000);
}
答案 1 :(得分:0)
在Runnable中进行更改。
public final Runnable mRunnable=new Runnable() {
@Override
public void run() {
TextView RX = (TextView)findViewById(R.id.RX);
TextView TX = (TextView)findViewById(R.id.TX);
TextView Totalbytes=(TextView)findViewById(R.id.TOTALX);
final long rxBytes=TrafficStats.getMobileRxBytes()-mStartRX;
RX.setText(Long.toString(rxBytes));
final long txBytes=TrafficStats.getMobileTxBytes()-mStartTX;
TX.setText(Long.toString(txBytes));
Totalbytes.setText(Long.toString(total_bytes));
long Txx=rxBytes;
long Rxx=txBytes;
total_bytes=Rxx+Txx;
if(total_bytes==1000){
// Display alert dialog here
mHandler.removeCallbacks(mRunnable);
}else{
mHandler.postDelayed(mRunnable, 1000);
}
}
};
希望这会对你有所帮助。