Android AppWidget电池状态

时间:2013-05-11 13:26:42

标签: android widget broadcastreceiver android-appwidget battery

我正在寻找一个可以检查电池状态的AppWidget(电平,充电/不充电)。

我写了很多代码行,但是,即使它完美运行,我也看到将它放在屏幕上使电话变慢,有时会崩溃。

我认为这是因为我做错了。有人能帮我吗?感谢的

这里我的清单:

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="it.bisneff.widgetone"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="10" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >


       <receiver android:name="MyWidgetProvider" >
            <intent-filter >
                <action 
                    android:name="android.appwidget.action.APPWIDGET_UPDATE" />

                <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
                <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>

            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widget_info" />
            </receiver>


    </application>

</manifest>

这是我的主要课程:

package it.bisneff.widgetone;


import it.bisneff.widgetone.R;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.RemoteViews;

public class MyWidgetProvider extends AppWidgetProvider {

    //Unused String
    private static final String ACTION_CLICK = "ACTION_CLICK"; 


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

        ComponentName thisWidget = new ComponentName(context,
            MyWidgetProvider.class);
        int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);

         for (int widgetId : allWidgetIds) {


                Intent batteryStatus =context.getApplicationContext().registerReceiver(this,
                        new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

                    //Battery Level
                int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);

                //Max Battery Level
                int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

                // %
                float batteryPct = level / (float)scale;
                batteryPct=batteryPct*100;



          RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
              R.layout.widget_layout);

          //Charging or not
          int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);


          boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                  status == BatteryManager.BATTERY_STATUS_FULL;

          //integer convertion
          int batteryPctz=(int)batteryPct;
          Log.w("WidgetExample", String.valueOf(batteryPctz)+"%");


          //USB or AC charge
          int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
          boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
          boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

          //update view
          remoteViews.setTextViewText(R.id.update, String.valueOf(batteryPctz)+"%");

          //select the image for the battery level
            String res=new String();
            res="it.bisneff.widgetone:drawable/battery";



                    if (batteryPct >= 90)
            {       res+="6";
            }
            if (batteryPct >= 75 && batteryPct < 90)
            {
                res+="5";
            }
            if (batteryPct >= 60 && batteryPct < 75 )
            {
            res+="4";
            }
            if (batteryPct >= 35 && batteryPct < 60 )
            {
            res+="3";
            }
            if (batteryPct >= 15 && batteryPct < 35 )
            {
            res+="2";
            }
            if (batteryPct < 15 )
            {
            res+="1";
            }


          if(isCharging){


            if(acCharge)
            {

                res+="cha";

            }


            if(usbCharge)
            {
            res+="usb";
            }


            if (batteryPctz==100){res="it.bisneff.widgetone:drawable/battery6full";}
          }

            //check the resource
            int reso= context.getResources().getIdentifier(res, null, null);    

            //put the right image
            remoteViews.setImageViewResource(R.id.imageView1, reso);



          //Set Click Listener

          Intent intent = new Intent(context, MyWidgetProvider.class);

          intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
          intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

          PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
              0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
          remoteViews.setOnClickPendingIntent(R.id.update, pendingIntent);
          appWidgetManager.updateAppWidget(widgetId, remoteViews);
        }

      }


      @Override
      public void onReceive(Context context, Intent intent) {
       super.onReceive(context, intent);

       //check received intent action
       if(  ((intent.getAction()).equals(Intent.ACTION_BATTERY_CHANGED)) || ((intent.getAction()).equals(Intent.ACTION_POWER_CONNECTED)) || ((intent.getAction()).equals(Intent.ACTION_POWER_DISCONNECTED))){

           //get Bundle
           Bundle extras = intent.getExtras();

           //if extras
           if(extras!=null) {


               AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);         
               ComponentName thisAppWidget = new ComponentName(context.getPackageName(), MyWidgetProvider.class.getName());
               int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidget);

          //call the onUpdate
          onUpdate(context, appWidgetManager, appWidgetIds);

         }

       }
      }

      }

编辑:

我知道问题在哪里。

如果我有

  ....
        Intent batteryStatus =context.getApplicationContext().registerReceiver(this,
                        new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
            context.getApplicationContext().unregisterReceiver(this);//this line
     ....

小部件停止循环。但它停止更新电池电量变化......

我添加了

@Override
public void onEnabled(Context context){

    context.getApplicationContext().registerReceiver(this, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

}

要确保注册我的接收器,但它不起作用,我无法从XML注册它因为文档说不能在那里注册。

我该怎么办?

1 个答案:

答案 0 :(得分:0)

你好Valerio Bisneff Ponza,

您必须面对此例外:

android.content.ReceiverCallNotAllowedException: BroadcastReceiver components are not allowed to register to receive intents

原因:这是因为,您(Widget / BroadCast接收器)无法从另一个Intent_Filter注册自己或从内部注册另一个接收器(Widget / BroadCast接收器)......

如果您在注册Widget时添加了清单:

  • 动作android:name =“android.intent.action.BATTERY_CHANGED”或
  • 动作android:name =“android.intent.action.ACTION_POWER_CONNECTED”或
  • 动作android:name =“android.intent.action.ACTION_POWER_DISCONNECTED”等。

...大部分时间你的Widget都不会响应。

原因:Widget与进程(pid)或服务相关联,如果独立运行(活动/服务)未运行,则不会接收Intents。

做什么呢?

在On Enabled中,启动服务,明确更新您的小部件,在onStart()服务中注册BroadCast接收器并从服务更新Widget。

注意:请记住在onStop()服务中取消注册接收者,否则会出现另一个异常......并从Widget的onDisabled()显式调用stopService()。如果需要,请在清单中将您的服务保持为exported =“false”,并在此处输入代码。

亲爱的Ponza,我有时会遇到这种情况,基于某些基于使用情况的GC,您的服务会被Android杀死。但在这种情况下,我们总是可以在Widget的每个操作中使用一些共享的Pref布尔值进行智能检查。

希望我的答案足够详细;)