好的,所以我正在开发一个 AppWidget,它检查电池电量并将其显示在 TextView 上。我的代码如下所示:
public class BattWidget extends AppWidgetProvider {
private RemoteViews views = new RemoteViews("com.nickavv.cleanwidgets", R.layout.battlayout);
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int appWidgetIds[]) {
final int N = appWidgetIds.length;
context.getApplicationContext().registerReceiver(this,new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
Log.d("onReceive", "Received intent " + intent);
if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
Integer level = intent.getIntExtra("level", -1);
views.setTextViewText(R.id.batteryText, level+"%");
AppWidgetManager myAWM = AppWidgetManager.getInstance(context);
ComponentName cn = new ComponentName(context, AirWidget.class);
onUpdate(context, myAWM, myAWM.getAppWidgetIds(cn));
}
}
}
我开始担心,因为一旦我将小部件放到我的主屏幕上,它就会开始每秒触发大约 100 个这样的 Log 调用,并说它正在接收 ACTION_BATTERY_CHANGED。这不应该只为每减少一个百分比而广播吗?它实际上导致我的整个启动器滞后,我不得不卸载它。这不可能。