每天在小部件中显示谚语 - Android

Display proverbs daily in a widget - Android

我做了一个小部件,应该每天显示一个随机谚语到目前为止一切正常,除了谚语没有改变,for testing purposes I set the timer for 3 secondes

这是我的代码:

JAVA

public class ProverbsWidget extends AppWidgetProvider {

public static int TIME_OUT = 3000; //1000 = 1 sec
public static String fnl_hv = RandomizedProverb(); //this is the method that generates the randem proverb and it's working fine

static void updateAppWidget(final Context context, final AppWidgetManager appWidgetManager,
                            final int appWidgetId) {

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // This method will be executed once the timer is over
                String widgetText = fnl_hv;

                // Construct the RemoteViews object
                RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.proverbs_widget);
                views.setTextViewText(R.id.sayings, widgetText);

                // Instruct the widget manager to update the widget
                appWidgetManager.updateAppWidget(appWidgetId, views);
            }
        },TIME_OUT);
}

RandomizeProverb() :

public static String RandomizedProverb(){
    Random rand = new Random();
    String [] Quotes = new String []{
            "test 1",
            "test 2",
            "test 3",
            "test 4",
            "test 5",
            "test 6",
            "test 7",
            "test 8",
            "test 9",
            "test 10",
            "test 11",
            "test 12",
            "test 13",
            "test 14",
            "test 15",
            "test 16",
            "test 17",
            "test 18",
            "test 19",
            "test 20",
    };

    String havm = Quotes[rand.nextInt(20)];
    String hav = havm;
    return hav;
}

显然问题出在我的计时器内,但我似乎无法让它工作

这样做:

Handler handler = new Handler();
Runnable runnable = new Runnable() {
            @Override
            public void run() {
                 // This method will be executed once the timer is over
                String widgetText = fnl_hv;

                // Construct the RemoteViews object
                RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.proverbs_widget);
                views.setTextViewText(R.id.sayings, widgetText);

                // Instruct the widget manager to update the widget
                appWidgetManager.updateAppWidget(appWidgetId, views);
                handler.postDelayed(runnable, timetoswitch);
            }
        },InitialDelayTime;

希望对您有所帮助!!!

这可以通过访问 XML 文件并将 updatePeriodMillis 的值设置为 86400000 来解决,如下所示:

android:updatePeriodMillis="86400000"

基本上这会告诉小部件何时更新自身,当时间到了时,方法 updateAppWidget() 将被执行,因为 86400000 是 24 小时内存在的毫秒数,小部件将每天更新