My app widget needs to be configured when it first added to the home screen. I want to open a configuration view right after the user adds the widget.
AppWidgetProvider
has no onCreated
event, so I'm showing the confugration activity on the onUpdate
event, and store a boolean value in SharedConfiguration
that marks that the configuration has already been shown. Is there an easier way?
In the AppWidgetProvider XML file there is an attribute called android:configure
You can use this to point to an Activity to launch when the app is dropped onto the home screen. ex:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:configure="com.bandsintown.WidgetSettingsActivity"
android:minWidth="250dp"
android:minHeight="110dp"
android:minResizeWidth="180dp"
android:minResizeHeight="110dp"
android:resizeMode="vertical|horizontal"
android:initialLayout="@layout/widget_layout"
android:updatePeriodMillis="10000" />
In your chosen configuration activity, the user can make whatever choice they want. You'll need to grab and store the widget's id. In the onCreate
method, get the id like this:
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null)
mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
When they've made their selection, use this to send a message back to your home screen widget that it is ready to be displayed:
Intent intent = new Intent();
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, intent);
finish();
That'll get what you're after.
Try to add it to the onEnabled function. onEnabled will be called when the app widget added to the screen
onEnabled(Context) This is called when an instance the App Widget is
created for the first time. For example, if the user adds two
instances of your App Widget, this is only called the first time. If
you need to open a new database or perform other setup that only needs
to occur once for all App Widget instances, then this is a good place
to do it.
for an example
@Override
public void onEnabled(Context context) {
Log.i("INDEX", "WIDGET Enabled");
AppWidgetManager mgr = AppWidgetManager.getInstance(context);
RemoteViews defaultViews = new RemoteViews(context.getPackageName(), R.layout.widget_restart);
Intent idefault = new Intent(context, MainActivity.class);
idefault.putExtra("widget", "1");
PendingIntent defaultpendingIntent = PendingIntent.getActivity(context, 0, idefault, 0);
defaultViews.setOnClickPendingIntent(R.id.headWidget, defaultpendingIntent);
ComponentName comp = new ComponentName(context.getPackageName(), Widget.class.getName());
mgr.updateAppWidget(comp, defaultViews);
}
this will be calle on the first time to set the appearance of the widget when the widget created for the first time
if you have any question feel free to ask me in the comment :)