Reputation: 998
I'm attempting to create an incredibly simple widget that changes the text displayed every 5s or so. However I've had major headaches attempting to get this to work. Obviously I can't use the onUpdate call as it's a minimum of every 30min. Currently my solution uses an Timer in an extended Service class, which is as ugly as hell and tends to run like a dog after a while. Is there a "clean" way of doing this, ie. in a manner that doesn't require a Widget, UpdateService, Timers etc.
I'm not asking for an entire solution, just a pointer as to how to go about doing this in an efficient manner.
Thanks, John
Upvotes: 1
Views: 630
Reputation: 1300
What i have done is added the below process that is called in your Widget Provider.... like so...
so the widget will update for the next 24 hours every 30secs....
I have also in my main app code I have a few prefs that I update and then I use the provider event to then call the timer that pulls the pref info.... updating with no service :)
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
try {
final int N = appWidgetIds.length;
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
updateAppWidget(context, appWidgetManager, appWidgetId);
}
updateWidgetView(context, context.getSharedPreferences(
MainActivity.APP_PREFERENCES,
Context.MODE_PRIVATE));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void updateAppWidget(final Context context, final AppWidgetManager appWidgetManager,
final int appWidgetId){
Context c;
c = context;
try {
new CountDownTimer(86400, 30000) {
public void onTick(long millisUntilFinished) {
//do proc every 30sec here. pull prefs and show them
SharedPreferences preferencesaa = PreferenceManager.getDefaultSharedPreferences(context);
String drinkmsg = preferencesaa.getString("WIDGETTEXT", "You need to drink water.");
RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget);
updateViews.setTextViewText(R.id.widget_text_threat, drinkmsg.toString());
appWidgetManager.updateAppWidget(appWidgetId, updateViews);
}
public void onFinish() {
}
}.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
First App that I am about to release. 8 Cups a Day™
Upvotes: 0
Reputation: 33901
Use a CountdownTimer
:
new CountdownTimer(5000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
Upvotes: 1