views:

80

answers:

1

I have a widget that displays an analog clock. What I would like is for the the widget to write to a database the time when a user clicks on the widget. I've already got the databaseHelper class and have an Activity that displays a screen showing the current date and time and writes the time to a database.

I followed the tutorial here: Analog Clock Tutorial and ended up with this:

public void onReceive(Context context, Intent intent)
{
    String action = intent.getAction();
    if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action))
    {
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
        this.mIntent = new Intent(context, AskTheTime.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, mIntent, 0);
        views.setOnClickPendingIntent(R.id.Widget, pendingIntent);

        AppWidgetManager.getInstance(context).updateAppWidget(intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS), views);
    }
}

The AskTheTime class extends activity and logs to the database in onCreate(). But this means that it displays only the time when the widget was started - not when it was clicked. (I guess this is because I'm starting a pendingIntent) I'm not sure If I should put the database write in another method or if I should be using Intents to do this sort of thing from widgets. Any pointers would be great! I've look at several tutorials for intents but none of them seem very clear to me.

+1  A: 

When your widget is pressed, the OS activates the pending intent you set on the widget. It looks like you are opening an activity AskTheTime when the widget is pressed. So the problem is that AskTheTime might have already been created when the widget is pressed, so the onCreate() isn't called again. What you could do is try doing your logging in onStart() or onResume() instead of, or in addition to, onCreate() inside your activity.

From the documentation regarding onStart:

Called when the activity is becoming visible to the user.

And onResume:

Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it.

mbaird