Battery Widget in Android

╄→尐↘猪︶ㄣ 提交于 2020-01-16 10:53:27

问题


Hi all I want to make a battery widget in android with animation. I think I will be able to animate but I want to know that how can I get the battery status again and again? Will it be OK to do it through thread? Or something else is required. Here is the simple code for animation. Please explain how will I get the data from battery again and again all the time.I know the functions but I don't know the mechanism to use them.

    public class HelloWidget  extends AppWidgetProvider{

    RemoteViews remoteViews;
    AppWidgetManager appWidgetManager;
    ComponentName thisWidget;
    ImageView img;
    Bitmap icon, icon1;
    int counter = 0;

    @Override
    public void onUpdate(Context context, final AppWidgetManager appWidgetManager,
    int[] appWidgetIds) {



        this.appWidgetManager = appWidgetManager;
        remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
        thisWidget = new ComponentName(context, HelloWidget.class);
        remoteViews.setImageViewResource(R.id.imgv, R.drawable.icon2);
        appWidgetManager.updateAppWidget(thisWidget, remoteViews);


        ( new Thread() 
        {

            public void run()
            {

                while(true)
                {
                    if(counter%15>=0 && counter%15 <=7)
                    {
                        remoteViews.setImageViewResource(R.id.imgv, R.drawable.icon2);
                    }
                    else
                    {
                        remoteViews.setImageViewResource(R.id.imgv, R.drawable.icon);
                    }
                    appWidgetManager.updateAppWidget(thisWidget, remoteViews);
                    counter++;
                }

             }

        }

            ).start();




}

回答1:


Register broadcast receiver for battery events and don't query every time.

IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
mContext.registerReceiver(batteryLevelReceiver, batteryLevelFilter);


来源:https://stackoverflow.com/questions/8063257/battery-widget-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!