Android: BatteryLevel widget not updating
I'm having some problems using RemoteViews. Simply want to make a widget that shows battery level. I've done all other stuffs already.
Here is my class:
public class BatteryLevel extends AppWidgetProvider{ public void onUpdate( Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds ){ context.startService(new Intent(context, BatteryMonitorReceiver.class)); } public static class BatteryMonitorReceiver extends Service{ private int currentBatteryLevel = 0; private BroadcastReceiver batteryReceiver = new BroadcastReceiver(){ @Override public void onReceive( Context context, Intent intent ){ currentBatteryLevel = intent.getIntExtra( "level", 0 ); } }; @Override public void onStart (Intent intent, int startId) { registerReceiver( this.batteryReceiver, new IntentFilter( Intent.ACTION_BATTERY_CHANGED ) ); RemoteViews updateViews = new RemoteViews( getPackageName(), R.layout.main ); updateViews.setTextViewText( R.id.level, String.valueOf(currentBatteryLevel)); ComponentName thisWidget = new ComponentName( this, BatteryLevel.class ); AppWidgetManager manager = AppWidgetManager.getInstance( this ); manager.updateAppWidget(thisWidget, updateViews); } @Override public IBinder onBind( Intent intent ){ return null; } } }
When i start the app no error and btw no update at R.id.level.
What's wrong?
Note: api version 7.
Since your service is an inner class, I guess you have not declared it in your Android Manifest, which is needed. And you shouldn't use onStart
, it is deprecated. Use onStartCommand
. And you forgot to unregister your receiver...