Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 637
Ogulcan Orhan Avatar asked Nov 07 '11 14:11

Ogulcan Orhan


1 Answers

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...

like image 56
Jong Avatar answered Sep 28 '22 08:09

Jong