Android电池电量检测问题

时间:2017-02-12 15:18:56

标签: java android batterylevel screen-brightness

我是stackoverflow的新用户,这是我的第一篇文章,如果我做错了什么,请随时告诉我,谢谢。

我正在开发一个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);

我不知道为什么它在广播接收器中完美无缺,但却没有按下按钮。

如果有人有想法解决这个问题或遇到同样的问题请帮助我,提前谢谢。

1 个答案:

答案 0 :(得分:1)

如果您检查documentation for BatteryManager.EXTRA_LEVEL,您会看到它是

  

包含当前电池电量的整数字段,从0到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 ;

修改

我刚刚重新阅读了您的代码,并且您看到0作为onClick方法的报告百分比并不会感到惊讶,您写道:

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

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

尝试更改您的意图以实际获得电池电量,然后使用我的上述修复来获得适当的百分比。

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