I'm trying to create a simple widget that displays the percentage of charge in both text and graphical way in widgets. The text part works without problems, but I have big difficulties with graphically updating the widget.
Graphically, I have a battery image that I shoot according to the percentage of battery. I am trying to use ClipDrawable for this.
battery_widget_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/widgetLayout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" android:padding="@dimen/widget_padding" android:background="@drawable/battery_clip_layer" > <TextView android:id="@+id/batteryPercentageWidgetTextView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="@string/battery_percentage_widget_default" android:gravity="center" /> </LinearLayout>
battery_clip_layer.xml (i.e. ClipDrawable)
<clip xmlns:android="http://schemas.android.com/apk/res/android" android:clipOrientation="vertical" android:gravity="bottom" android:drawable="@drawable/battery_shape" />
BatteryService.java - a service that receives battery events and updates the widget via RemoteViews
public class BatteryService extends Service { private static final String LOG = BatteryService.class.getName(); private final AtomicInteger batteryPercentage = new AtomicInteger(100); private final BroadcastReceiver batteryUpdateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int level = intent.getIntExtra("level", 0); batteryPercentage.set(level); updateWidget(); } }; @Override public void onCreate() { super.onCreate(); registerReceiver(batteryUpdateReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); Log.i(LOG, "Created..."); } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(batteryUpdateReceiver); Log.i(LOG, "Destroyed..."); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i(LOG, "Started..."); updateWidget(); return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent arg0) { return null; } private void updateWidget() { final int percentage = batteryPercentage.get(); log.i(LOG, "Updated... " + percentage); RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.battery_widget_layout); remoteViews.setTextViewText(R.id.batteryPercentageWidgetTextView, percentage + "%");
In BatteryService check out two different attempts to update the widget ( updateWidget() and updateWidgetAttempt2() ). Not a single attempt failed.
I feel that I am doing something fundamentally wrong. I am very grateful for any help / advice! :)