简体   繁体   中英

Android Battery Level Detect Issue

I am a new user to stackoverflow, this is my first post, if I have done anything wrong please feel free to tell me, thanks.

I am developing an android application to monitor the battery level and change screen brightness, but I were got a weird problem and cannot find it after googling many times.

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);
            }
        }
    }
}

}

When I test it in real device The code above works fine, but I want to set the screen brightness instantly when user enabled this options, so I use this code to do action when user click on the button.

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;
}

}

But the problem is, when I test on real device even my device battery level is above 50%

when I click the button the screen brightness is changed to 10, this also means this code is executed.

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

I have no idea why it works perfectly in broadcast receiver but not working with the button click.

If anyone have an idea to solve this or encountered same issue before please help me, thanks in advance.

If you check the documentation for BatteryManager.EXTRA_LEVEL you would see that it is

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

EXTRA_SCALE being another value available for you to grab, my assumption here, and the issue that you are facing, is the scale is probably 1.0, meaning that 20% battery would actually be .20

To properly calculate the battery percentage, on a 0 -> 100 scale, use the following

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

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

edit

I just re-read your code, and am not surprised that you are seeing 0 as a reported percentage for your onClick method, you have written:

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

Here, you are trying to get data from an intent that you just created, not one that actually contains the data you are looking for.

Try changing your intent to this to actually get the battery level, then use my above fix to get the proper percentage.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM