Android 电池电量检测问题

Android Battery Level Detect Issue

我是Whosebug的新用户,这是我的第一个post,如果我做错了什么请随时告诉我,谢谢。

我正在开发一个 android 应用程序来监控电池电量和更改屏幕亮度,但我遇到了一个奇怪的问题,在谷歌搜索了很多次后都找不到它。

public class SmartBrightnessProcessor extends BroadcastReceiver{

Context mContext;
IntentFilter intentFilter;
ContentResolver contentResolver;

public SmartBrightnessProcessor(Context context){
    this.mContext = context;
    intentFilter = new IntentFilter();
    intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
}
public void registerReceiver(){
    mContext.registerReceiver(this, intentFilter);
}
public void unRegisterReceiver(){
    mContext.unregisterReceiver(this);
}
@Override
public void onReceive(Context context, Intent intent){

    contentResolver = context.getContentResolver();

    boolean isEnabled = context.getSharedPreferences("SmartBrightness",
            Context.MODE_PRIVATE).getBoolean("SmartBrightness", false);

    int batteryLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);

    if(isEnabled){
        if(Build.VERSION.SDK_INT >= 23){
            if(Settings.System.canWrite(context)){
                if(batteryLevel >= 70){
                    Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, 85);
                }else if(batteryLevel >= 50 && batteryLevel <= 69){
                    Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, 70);
                }else if(batteryLevel >= 20 && batteryLevel <= 49){
                    Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, 50);
                }else if(batteryLevel >= 10 && batteryLevel <= 19){
                    Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, 30);
                }else if(batteryLevel <= 9){
                    Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, 10);
                }
            }
        }else{
            if(batteryLevel >= 70){
                Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, 85);
            }else if(batteryLevel >= 50 && batteryLevel <= 69){
                Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, 70);
            }else if(batteryLevel >= 20 && batteryLevel <= 49){
                Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, 50);
            }else if(batteryLevel >= 10 && batteryLevel <= 19){
                Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, 30);
            }else if(batteryLevel <= 9){
                Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, 10);
            }
        }
    }
}

}

当我在真实设备上测试时上面的代码工作正常,但我想在用户启用此选项时立即设置屏幕亮度,所以我使用此代码在用户单击按钮时执行操作。

public class SmartBrightness extends Fragment {

SharedPreferences sharedPreferences;
Context context;
ContentResolver contentResolver;
Intent intent;
int batteryLevel;
Switch aSwitch;

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){

    View view = inflater.inflate(R.layout.smart_brightness, container, false);

    context = getActivity().getApplicationContext();

    sharedPreferences = getActivity().getSharedPreferences("SmartBrightness", 0);
    Boolean smartBrightness = sharedPreferences.getBoolean("SmartBrightness", false);

    aSwitch = (Switch)view.findViewById(R.id.switch1);

    aSwitch.setChecked(smartBrightness);

    intent = new Intent();

    contentResolver = context.getContentResolver();

    batteryLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);

    aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked){
                if(Build.VERSION.SDK_INT >= 23){
                    if(!writeSettingsPermissionGranted()){
                        showMissingPermissionDialog();
                        aSwitch.setChecked(false);
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putBoolean("SmartBrightness", false);
                        editor.apply();
                    }else{
                        if(batteryLevel >= 70){
                            Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, 85);
                        }else if(batteryLevel >= 50 && batteryLevel <= 69){
                            Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, 70);
                        }else if(batteryLevel >= 20 && batteryLevel <= 49){
                            Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, 50);
                        }else if(batteryLevel >= 10 && batteryLevel <= 19){
                            Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, 30);
                        }else if(batteryLevel <= 9){
                            Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, 10);
                        }
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putBoolean("SmartBrightness", true);
                        editor.apply();
                    }
                }else{
                    if(batteryLevel >= 70){
                        Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, 85);
                    }else if(batteryLevel >= 50 && batteryLevel <= 69){
                        Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, 70);
                    }else if(batteryLevel >= 20 && batteryLevel <= 49){
                        Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, 50);
                    }else if(batteryLevel >= 10 && batteryLevel <= 19){
                        Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, 30);
                    }else if(batteryLevel <= 9){
                        Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, 10);
                    }
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putBoolean("SmartBrightness", true);
                    editor.apply();
                }
            }else{
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putBoolean("SmartBrightness", false);
                editor.apply();
            }
        }
    });

    return view;
}
private void requestWriteSettingsPermission(){
    if(Build.VERSION.SDK_INT >= 23){
        Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}
public void showMissingPermissionDialog(){
    final ViewGroup nullParent = null;
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
    LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
    View view = layoutInflater.inflate(R.layout.write_settings_explaination, nullParent);

    alertDialog.setView(view);
    alertDialog.setCancelable(false);
    alertDialog.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            requestWriteSettingsPermission();
            dialog.dismiss();
        }
    });
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    alertDialog.show();
}
public boolean writeSettingsPermissionGranted(){
    if(Build.VERSION.SDK_INT >= 23){
        if(android.provider.Settings.System.canWrite(context)){
            return true;
        }
    }
    return false;
}

}

但问题是,当我在真实设备上测试时,即使我的设备电池电量超过 50%

当我点击按钮时,屏幕亮度变为 10,这也意味着这段代码被执行了。

Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, 10);

我不知道为什么它在广播接收器中工作得很好,但点击按钮却不工作。

如果有人有解决此问题的想法或之前遇到过同样的问题,请帮助我,在此先感谢。

如果您检查 documentation for BatteryManager.EXTRA_LEVEL,您会发现它是

integer field containing the current battery level, from 0 to EXTRA_SCALE.

EXTRA_SCALE 是另一个可供您获取的值,我在这里的假设以及您面临的问题是比例可能是 1.0,这意味着 20% 的电池实际上是 .20

要在 0 -> 100 范围内正确计算电池百分比,请使用以下内容

batteryLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
levelScale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);

double realPercent = (((double)batteryLevel) / levelScale) * 100 ;

编辑

我只是 re-read 你的代码,当你看到 0 作为 onClick 方法的报告百分比时,我并不感到惊讶,你写了:

intent = new Intent();
batteryLevel = intent.getIntExtra(...);

在这里,您正在尝试从刚刚创建的意图中获取数据,而不是实际包含您要查找的数据的意图。

尝试将您的意图更改为此以实际获取电池电量,然后使用我上面的修复来获取正确的百分比。

Intent batteryIntent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));