1

我正在尝试制作一个显示电池电量的电池小部件。当它启动时,它工作正常,但一段时间后,它停止工作并开始显示电池电量 0。请帮我弄清楚我错过了什么。

这是代码:

public class Widget extends AppWidgetProvider {
    static int level;
static int powers;
AppWidgetManager ap;

@Override
public void onReceive(final Context context, Intent intent) {
    // TODO Auto-generated method stub
    super.onReceive(context, intent);

    System.out.println(intent.getAction());

    if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BATTERY_CHANGED)) {

        int rawlevel = intent.getIntExtra("level", -1);
        int scale = intent.getIntExtra("scale", -1);

        powers = intent.getIntExtra("plugged", -1);

        level = -1;
        if (rawlevel >= 0 && scale > 0) {
            level = (rawlevel * 100) / scale;
        }
        onUpdatew(context);

    }
}

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {
    final int N = appWidgetIds.length;
    for (int i = 0; i < N; i++) {
        int appWidgetId = appWidgetIds[0];

        Intent intent = new Intent(context, xyz.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                intent, 0);

        RemoteViews views = new RemoteViews(context.getPackageName(),
                R.layout.widget_main);

        views.setTextViewText(R.id.txt1, level + "");
        Log.i("Power", powers + "");
        Log.i("Level", level + "");

        views.setOnClickPendingIntent(R.id.iv, pendingIntent);
        appWidgetManager.updateAppWidget(appWidgetId, views);

        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }

}

@Override
public void onEnabled(Context context) {
    // TODO Auto-generated method stub
    System.out.println(context.getApplicationContext().registerReceiver(
            this, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)));
    onUpdatew(context);
    super.onEnabled(context);
}

public void onUpdatew(Context context) {
    RemoteViews views = new RemoteViews(context.getPackageName(),
            R.layout.widget_main);

    views.setTextViewText(R.id.txt1, level + "");

    AppWidgetManager myManager = AppWidgetManager.getInstance(context);
    ComponentName myName = new ComponentName(context, Widget.class);
    myManager.updateAppWidget(myName, views);

}}
4

0 回答 0