我尝试输入一些代码,但未与手机电池同步 例如:我的手机电池电量为72%,但始终显示100%不会上升或下降。此代码不需要任何特殊权限
public class MainActivity extends AppCompatActivity {
private Context mContext;
private TextView mViewInfo;
private TextView mViewPercentage;
private ProgressBar mProgressBar;
private int mProgressStatus = 0;
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
mViewInfo.setText("Battery Scale : " + scale);
int level = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
mViewInfo.setText(mViewInfo.getText() + "\nBattery Level : " + level);
float percentage = level/ (float) scale;
mProgressStatus = (int)((percentage)*100);
mViewPercentage.setText("" + mProgressStatus + "%");
mViewInfo.setText(mViewInfo.getText() + "\nPercentage : " + mProgressStatus + "%");
mProgressBar.setProgress(mProgressStatus);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_ACTION_BAR);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = getApplicationContext();
IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
mContext.registerReceiver(mBroadcastReceiver, iFilter);
mViewInfo = (TextView) findViewById(R.id.tv_info);
mViewPercentage = (TextView) findViewById(R.id.tv_percentage);
mProgressBar = (ProgressBar) findViewById(R.id.pb);
}
}
我希望我的代码可以与手机电池同步 总是说所有100%的假设都是要与电池同步的
答案 0 :(得分:0)
您的问题是由这段代码引起的:
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
mViewInfo.setText("Battery Scale : " + scale);
int level = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
mViewInfo.setText(mViewInfo.getText() + "\nBattery Level : " + level);
float percentage = level/ (float) scale;
mProgressStatus = (int)((percentage)*100);
如果您注意到了,您会发现同时使用intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
的 scale 和 level 。
这意味着您将获得完全相同的值,所以当您进行level / (float) scale;
的计算时,您几乎正在执行NUM / NUM
,这将始终等于到1。然后当您执行1 * 100
时,它将始终等于100。
您需要做的是更换:
int level = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
具有:
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);