插件几分钟后停止更新 [英] Widget stops updating after a few minutes

查看:167
本文介绍了插件几分钟后停止更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即时通讯开发一个小部件可显示使用时间和日期两个的TextView 使用定时来每秒更新一次:

Im developing a widget that shows the time and date using two TextView using a timer to update every second:

final Handler handler = new Handler();
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {

            handler.post(new Runnable() {
                    public void run() {
                        java.util.Date noteTS = Calendar.getInstance().getTime();
                        String time = "kk:mm";
                        String date = "dd MMMMM yyyy";

                        views.setTextViewText(R.id.tvTime, DateFormat.format(time, noteTS));
                        views.setTextViewText(R.id.tvDate, DateFormat.format(date, noteTS));
                        appWidgetManager.updateAppWidget(appWidgetId, views);
                    }
            });
    }
}, 0, 1000);// Update textview every second

有更新微件时添加,但几分钟后停止。此外,它挣扎着我重新启动后加载,但主要问题是,它似乎这么多分钟后,定时停止...
任何人都知道是怎么回事?谢谢

It updates the widget when added but stops after a few minutes. Also it struggles to load after I reboot but the main problem is it seems the timer stops after so many minutes... Anyone know what is going on? Thanks

推荐答案

由于应用程序插件只能由主屏幕进程承载的广播接收器,你必须使用 AlarmManager 调度调用您的小部件。如果不是只是为了测试要知道,你的电池会耗尽,因为该设备永远不会进入睡眠状态。一般来说是不更新应用程序部件一个好主意,每一秒。

As app widget is only a broadcast receiver hosted by the home screen process, you have to use AlarmManager for scheduling calls to your widget. If it is not just for testing be aware that your battery will drain because the device will never go to sleep state. Generally it is not a good idea to update app widgets every second.

这是可以做到(这里唤醒在一分钟内)与此类似code

It could be done (here for a wake up in one minute) similar to this code

AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(MyWidget.ACTION_MYACTION);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
long triggerAtTime = getNextOccurrence(1); // next minute
am.set(AlarmManager.RTC_WAKEUP, triggerAtTime, pi);

static private long getNextOccurrence(int deltaMinutes)
    {
            Calendar calendar = Calendar.getInstance();
            long now = calendar.getTimeInMillis();
            long then = now + (deltaMinutes * 60 * 1000);
            return then;
    }

的onReceive

public void onReceive(Context context, Intent intent)
    {
            Log.d(TAG, "onReceive() " + intent.getAction());
            super.onReceive(context, intent);

            if (intent != null)
            {
                    if (ACTION_MYACTION.equals(intent.getAction())
                    {
                            updateWidgets(context);
                    }
             ...

这篇关于插件几分钟后停止更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆