gpt4 book ai didi

java - 为什么我的低电量警报代码不起作用?

转载 作者:行者123 更新时间:2023-11-29 23:19:23 25 4
gpt4 key购买 nike

我尝试发出低电量警报,但我的代码不起作用,它始终显示 Toast即使我设置了所有级别的按摩< 30也许某些东西丢失了或者我的代码是错误的?还有Toast当我点击屏幕时会消失,即使我设置了toast.setDuration(Toast.LENGTH_LONG);

public void onReceive(Context context, Intent intent) {
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int lowLevel = intent.getIntExtra("Level", 0);

float percentage = level/ (float) scale;
mProgressStatus = (int)((percentage)*100);
mViewPercentage.setText("" + mProgressStatus + "%");
mProgressBar.setProgress(mProgressStatus);

if (lowLevel < 30){

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.lowbattery_toast, (ViewGroup) findViewById(R.id.low_battery));
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 10);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);

toast.show();
}
}

有什么办法可以解决我的问题吗?

最佳答案

我猜您正在尝试制作一个低电量警报,并在电池电量低于 30% 时显示 Toast。

您的进度条应该可以正常工作,但在 BatteryManager 的文档中您可以看到常量 BatteryManager.EXTRA_LEVEL 等于“level”而不是“Level”,因此您的代码没有获得正确的值。

要让 Toast 正常工作,您必须修改以下行:

 int lowLevel = intent.getIntExtra("Level", 0);

这个

 int lowLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);

(更新)

这样,每当您的电池电量低于阈值时(例如,当它是 29、28、27 时...),都会显示 Toast。要修复它,一个简单的方法是这样的:

private static int previousLevel = 100;

public void onReceive(Context context, Intent intent) {
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int lowLevel = intent.getIntExtra("Level", 0);

float percentage = level/ (float) scale;
mProgressStatus = (int)((percentage)*100);
mViewPercentage.setText("" + mProgressStatus + "%");
mProgressBar.setProgress(mProgressStatus);

if (lowLevel < 30 && previousLevel >= 30){

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.lowbattery_toast, (ViewGroup) findViewById(R.id.low_battery));
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 10);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);

toast.show();
}

previousLevel = lowLevel;
}

关于java - 为什么我的低电量警报代码不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54671245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com