This is a battery widget. This is not my code but taken from http://www.cmwmobile.com/index.php?option=com_content&view=article&id=56&Itemid=68.

private final BroadcastReceiver batteryChangedReceiver = new
                BroadcastReceiver() {
            /**
             * {@inheritDoc}
             */
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();

                if (action != null && action.equals(
                        Intent.ACTION_BATTERY_CHANGED)) {
                    int rawLevel = intent.getIntExtra(
                        BatteryManager.EXTRA_LEVEL, -1);
                    int scale = intent.getIntExtra(
                        BatteryManager.EXTRA_SCALE, 1);

                    if (scale > 0) {
                        batteryLevel = rawLevel * 100 / scale;
                    }
                    else {
                        batteryLevel = rawLevel;
                    }

                    intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
                    intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
                    intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);

                    updateBattery(context);
                }
                else if (action != null && action.equals(ACTION_UPDATE)) {
                    updateBattery(context);
                }
            }
        };

What i need to change is two things.

1) (SOLVED) I need to implement the % symbol after the battery level and i don't know how do it. I've tried batteryLevel = rawLevel + "%"; but gets me an error.

2) Actually this widget has a background color only and not an image.. If i would an image as background how could do besides change background in xml layout? I mean programmatically i want change image when battery level change. For example if the battery level is 80 then img1, if 70 then img2 etc etc.

EDIT: Point one solved.

有帮助吗?

解决方案

2)With the method setImageResource (or setImageBitmap,... ImageView documentation)

ImageView img = new ImageView(this);
img.setResource(R.drawable.image);

其他提示

2) If your .xml file got for example LinearLayout,

LinearLayout layout = (LinearLayout) findViewById(R.id.your_layout_id);
switch(batteryLevel){
case 80:
    layout.setBackgroundResource(R.drawable.image_for_80);
    break;
case 70:
    layout.setBackgroundResource(R.drawable.image_for_70);
    break;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top