1

我有一个 android 小部件,我想每 5 秒更新一次它自己的 textview。

将其视为一个新闻小部件,其中最重要的新闻将一次显示在小部件上。出于演示目的,我将只使用一个数组来向您展示不同的文本。

代码是这样的:

public class ListingsWatchWidget extends AppWidgetProvider {

    private static int WIDGET_REFRESH_TIME = 5;
    public Handler handler = new Handler();

    //private RemoteViews views;    
    private int REFRESH_COUNT = 0;
    private String[] titles = {"Title 1", "Title 2", "Title 3"};

    public boolean killMe = false;

    private Context ctx;

    Runnable updateWidgetText = new Runnable()
    {
        @Override
        public void run() {

        Log.i("ListingsWatchWidget", "killMe is " + ListingsWatchWidget.this.killMe);
        if (ListingsWatchWidget.this.killMe) { return; }

        AppWidgetManager gm = AppWidgetManager.getInstance(ctx);                        
        ComponentName thisWidget = new ComponentName(ctx, ListingsWatchWidget.class);         

        int index = (int)(REFRESH_COUNT % titles.length);
        Log.i("ListingsWatchWidget", "index = " + index);

        RemoteViews views = new RemoteViews(ctx.getPackageName(),R.layout.widget);    
        views.setTextViewText(R.id.titleTextView, titles[index]);  

        gm.updateAppWidget(thisWidget, views);

        REFRESH_COUNT++;

        handler.postDelayed(this, WIDGET_REFRESH_TIME * 1000);

        }   
    };  


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

        Log.i("ListingsWatchWidget", intent.getAction());

        if (intent.getAction().equals("android.appwidget.action.APPWIDGET_ENABLED")) {
            handler.removeCallbacks(updateWidgetText);
            ctx = context;
            handler.postDelayed(updateWidgetText, WIDGET_REFRESH_TIME*1000);
        }
        else if (intent.getAction().equals("android.appwidget.action.APPWIDGET_DISABLED")) {
            handler.removeCallbacks(updateWidgetText);
            this.killMe = true;
        }

    }

    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        //TODO ...
    }

}

一切都按预期工作,除非用户从他的桌面上删除小部件。runnable 继续无休止地运行。

我已经尝试过各种解决方案,如thisthis但没有一个有效。

让我给你一个片段,如果记录器在将小部件添加到桌面和删除它时:

06-20 22:22:57.318: I/ListingsWatchWidget(4012): android.appwidget.action.APPWIDGET_ENABLED
06-20 22:22:57.328: I/ListingsWatchWidget(4012): android.appwidget.action.APPWIDGET_UPDATE
06-20 22:23:02.323: I/ListingsWatchWidget(4012): killMe is false
06-20 22:23:02.323: I/ListingsWatchWidget(4012): index = 0
06-20 22:23:06.857: I/ListingsWatchWidget(4012): android.appwidget.action.APPWIDGET_DELETED
06-20 22:23:06.877: I/ListingsWatchWidget(4012): android.appwidget.action.APPWIDGET_DISABLED
06-20 22:23:07.338: I/ListingsWatchWidget(4012): killMe is false
06-20 22:23:07.338: I/ListingsWatchWidget(4012): index = 1

小部件被删除后,runnable 应该停止...

4

0 回答 0