简体   繁体   中英

How to update widget every minute

can anyone tell me the best way to update widget every minute.

Now i'm using thread inside the AppWidget, but sometimes i get error FAILED BINDER TRANSACTION !!! After that error, i always got a lot of error like that all the time and i can't change the view in my widget again.

Thanks

Rather than using a thread in the AppWidget, you would be better served by using the AlarmManager to schedule a repeating AppWidget Update Intent which your code would handle appropriately.

The benefits of this approach is the possibility to configure the update rate, and also handle the case of the device sleeping (and not waking up to run your code, or even being blocked from sleeping because your thread is busy).

There are numerous examples around the internet that should explain the ins and outs of using the AlarmManager to raise your AppWidget Update Intents.

The system sends a broadcast event at the exact beginning of every minutes based on system clock. Create a service with your widget and do something like this :

BroadcastReceiver _broadcastReceiver;
private final SimpleDateFormat _sdfWatchTime = new SimpleDateFormat("HH:mm");
private TextView _tvTime;

@Override
public void onStart() {
    super.onStart();
    _broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context ctx, Intent intent) {
                if (intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0)
                    _tvTime.setText(_sdfWatchTime.format(new Date()));
            }
        };

    registerReceiver(_broadcastReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}

@Override
public void onStop() {
    super.onStop();
    if (_broadcastReceiver != null)
        unregisterReceiver(_broadcastReceiver);
}

Don't forget however to initialize your TextView beforehand (to current system time) since it is likely you will pop your UI in the middle of a minute and the TextView won't be updated until the next minute happens.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM