0

我想使用服务来测量自该服务启动以来使用的移动数据,但我只能使用 TrafficStats 类的 getTotalRxBytes() 和 getTotalTxBytes() 方法测量设备启动后的移动数据。有人可以帮我测量单击按钮并启动服务时使用的数据吗?

MainActivity.java

public class MainActivity extends AppCompatActivity {

private long data_limit;
EditText et_data_limit;
Button btn_start_track;
private int STORAGE_PERMISSION_CODE = 23;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
int PRIVATE_MODE = 0;

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    sharedPreferences = MainActivity.this.getSharedPreferences("Data measured", PRIVATE_MODE);
    editor = sharedPreferences.edit();

    editor.putLong("data", 0);

    if(isPermissionAllowed()){

    }
    else{
        requestPermission();
    }

    et_data_limit = (EditText)findViewById(R.id.et_data_limit);
    btn_start_track = (Button)findViewById(R.id.btn_start_track);

    btn_start_track.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            data_limit = Long.parseLong(et_data_limit.getText().toString());
            data_limit = data_limit * 1024;

            Log.i("enter", String.valueOf(data_limit));

            //data_limit = data_limit + sharedPreferences.getLong("data", 0);

            editor.putLong("data", data_limit);
            editor.commit();

            Intent intent = new Intent(MainActivity.this, DataTracking.class);
            intent.putExtra("data limit", data_limit);

            MainActivity.this.startService(intent);
        }
    });
}

private boolean isPermissionAllowed() {
    //Getting the permission status
    int result = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_WIFI_STATE);
    int result1 = ContextCompat.checkSelfPermission(this, Manifest.permission.CHANGE_WIFI_STATE);
    int result2 = ContextCompat.checkSelfPermission(this, Manifest.permission.MODIFY_PHONE_STATE);

    //If permission is granted returning true
    if (result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED &&
            result2 == PackageManager.PERMISSION_GRANTED)
        return true;

    //If permission is not granted returning false
    return false;
}

private void requestPermission(){

    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_WIFI_STATE) &&
            ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CHANGE_WIFI_STATE) &&
            ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.MODIFY_PHONE_STATE)){
        //If the user has denied the permission previously your code will come to this block
        //Here you can explain why you need this permission
        //Explain here why you need this permission
    }

    //And finally ask for the permission
    ActivityCompat.requestPermissions(this,new String[]{
            Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.CHANGE_WIFI_STATE,
    Manifest.permission.MODIFY_PHONE_STATE},STORAGE_PERMISSION_CODE);
}

//This method will be called when the user will tap on allow or deny
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    //Checking the request code of our request
    if(requestCode == STORAGE_PERMISSION_CODE){

        //If permission is granted
        if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){

            //Displaying a toast
            Toast.makeText(this,"Permission granted!",Toast.LENGTH_LONG).show();
        }else{
            //Displaying another toast if permission is not granted
            Toast.makeText(this,"Permission denied! App may not work properly",Toast.LENGTH_LONG).show();
        }
    }
}
}

数据跟踪.java

public class DataTracking extends Service {

private long data_limit;
private long data_used;

public DataTracking(){

}

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId){

    data_limit = intent.getExtras().getLong("data limit");
    Log.i("data", String.valueOf(data_limit));
    Toast.makeText(getApplicationContext(), "Service started", Toast.LENGTH_SHORT).show();

    onHandleIntent(intent);

    return Service.START_STICKY;
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

protected void onHandleIntent(@Nullable Intent intent) {

    TrafficStats trafficStats = new TrafficStats();

    long mtx = TrafficStats.getMobileTxBytes();
    long mrx = TrafficStats.getMobileRxBytes();

    data_used = mtx + mrx;

    Toast.makeText(getApplicationContext(), data_used + "-" + data_limit, Toast.LENGTH_SHORT).show();

    if(data_used >= data_limit){
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiManager.setWifiEnabled(true);

        try{
            TelephonyManager telephonyManager = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
            Method setMobileDataStatus = telephonyManager.getClass().getDeclaredMethod("setDataEnabled", boolean.class);

            if (null != setMobileDataStatus){
                setMobileDataStatus.invoke(telephonyManager, false);
                stopSelf();
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}
}
4

0 回答 0