안녕하세요 저는 사용자의 데이터 소비를 모니터링하는 안드로이드 응용 프로그램을 만들고 있습니다. 모든 것이 지금까지 부풀어 오르고 있습니다. 그러나 나는 걸림돌을 때 렸습니다, 나는 마지막으로 소비 된 데이터를 저장하고 싶었고 다시 서비스를 시작할 때 마지막으로 소비 된 데이터 등에서 시작할 것입니다.마지막부터 시작 Received Bytes TrafficStats
이 내 서비스 클래스 :
//THIS METHOD IS CALLED EVERY 3 seconds to check for new DATA CONSUMED
public void displayNotificationWIFI() {
sharedPreferences = getSharedPreferences(SHARED_PREF_WIFI, Context.MODE_PRIVATE);
consumed = sharedPreferences.getString(WIFI_DATA_BYTES, null);
//CHECK IF CONSUMED IS NULL, IF NULL GET NEW DATA CONSUMED
if (consumed == null) {
rxBytes = TrafficStats.getTotalRxBytes() - mStartRX;
if (rxBytes >= 1024) {
rxKB = rxBytes/1024;
received = String.format("%.0f", rxKB);
unit = "KB";
if (rxKB >= 1024) {
DecimalFormat formatMB = new DecimalFormat("0.0");
rxMB = rxKB/1024;
received = formatMB.format(rxMB);
unit = "MB";
if (rxMB >= 1024) {
DecimalFormat formatGB = new DecimalFormat("0.0");
rxGB = rxMB/1024;
received = formatGB.format(rxGB);
unit = "GB";
}
}
sharedPreferences = getSharedPreferences(SHARED_PREF_WIFI, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(WIFI_DATA_BYTES, String.valueOf(rxBytes));
editor.putString(WIFI_DATA, received + " " + unit);
editor.apply();
}
}
//SINCE NOT NULL, START FROM LAST DATA CONSUMED
else {
//STARTS FROM LAST DATA CONSUMED, BUT I THINK THIS IS WRONG?
rxBytes = (TrafficStats.getTotalRxBytes() - mStartRX) + Double.parseDouble(consumed);
if (rxBytes >= 1024) {
rxKB = rxBytes/1024;
received = String.format("%.0f", rxKB);
unit = "KB";
if (rxKB >= 1024) {
DecimalFormat formatMB = new DecimalFormat("0.0");
rxMB = rxKB/1024;
received = formatMB.format(rxMB);
unit = "MB";
if (rxMB >= 1024) {
DecimalFormat formatGB = new DecimalFormat("0.0");
rxGB = rxMB/1024;
received = formatGB.format(rxGB);
unit = "GB";
}
}
//SAVING THE NEW LAST CONSUMED DATA
sharedPreferences = getSharedPreferences(SHARED_PREF_WIFI,Context.MODE_PRIVATE);
SharedPreferences.Editor editors = sharedPreferences.edit();
editors.putString(WIFI_DATA_BYTES, String.valueOf(rxBytes));
editors.apply();
}
}
remoteView = new RemoteViews(getPackageName(), R.layout.custom_notification_pingwifi);
remoteView.setTextViewText(R.id.txtData, received + " " + unit);
NotificationCompat.Builder n = new NotificationCompat.Builder(serviceClass.this);
n.setCustomContentView(remoteView)
.setSmallIcon(R.mipmap.ic_launcher)
.setOngoing(true);
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, n.build());
}
내 코드의 문제는 서비스가 다시 시작될 때이다. 이전 데이터는 새로운 데이터를 추가하기 만하면 인터넷을 사용하지 않아도 추가 및 추가되고 멈추지 않습니다.
3 초마다 반복하면 기기의 배터리에 심각한 부정적 영향을 미칩니다. –