我有一个电池小部件,由于某种原因,当手机插入AC时,它没有收到BATTERY_PLIGGED_AC
整数。
我有BATTERY_PLUGGED_USB
的另一个小部件,效果很好。
我看不出我的代码有什么问题:
public void onReceive(Context context, Intent intent) {
status = intent.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN);
batterylevel = intent.getIntExtra("level", 0);
updateAppWidget(context);
}
public void updateAppWidget(Context context){
RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.androidbatterywidget_layout);
updateViews.setTextViewText(R.id.textView1, " " + batterylevel + "%");
if (status == BatteryManager.BATTERY_PLUGGED_USB)
updateViews.setImageViewResource(R.id.imageView2, R.drawable.usb);
else if (status == BatteryManager.BATTERY_PLUGGED_AC)
updateViews.setImageViewResource(R.id.imageView2, R.drawable.bolt);
else
updateViews.setImageViewResource(R.id.imageView2, R.drawable.empty);
希望有人能够发现我做错了什么。谢谢!
答案 0 :(得分:1)
想办法。对不起,这篇文章我应该再看一会儿了。为了将来参考,如果人们似乎有同样的问题,在我看来,USB值与BatteryManager.BATTERY_STATUS_UNKNOWN捆绑,但不是AC。所以我所做的只是将一个新的私人int charge指定给BatteryManager.BATTERY_PLUGGED_AC变量的值。如果这是真的(并且设备正在为throygh AC充电),那么值为1,所以我只是用
替换了我以前的if语句if (charging == 1)
updateViews.setImageViewResource(R.id.imageView2, R.drawable.bolt);
现在代码读取;
private int batterylevel = 0;
private int status;
private int charging;
private BroadcastReceiver myReceiver = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
status = intent.getIntExtra("status", BatteryManager.BATTERY_HEALTH_UNKNOWN);
charging = intent.getIntExtra("plugged", BatteryManager.BATTERY_PLUGGED_AC);
batterylevel = intent.getIntExtra("level", 0);
updateAppWidget(context);
}
public void updateAppWidget(Context context){
RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.androidbatterywidget_layout);
updateViews.setTextViewText(R.id.textView1, " " + batterylevel + "%");
if (charging == 1)
updateViews.setImageViewResource(R.id.imageView2, R.drawable.bolt);
else if (status == BatteryManager.BATTERY_PLUGGED_USB)
updateViews.setImageViewResource(R.id.imageView2, R.drawable.usb);
else
updateViews.setImageViewResource(R.id.imageView2, R.drawable.empty);
我确信有一个更“雄伟”的方法来做到这一点,但我只是感到困惑的是,为什么USB int被传递,如果它插入USB(2),而不是AC(1)。 / p>
谢谢!