Runnable不会停在Android Widget上

时间:2012-06-20 18:59:49

标签: android android-widget runnable

我有一个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 ...
    }

}

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

我尝试了各种解决方案建议为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应该停止...

0 个答案:

没有答案