Skip to content Skip to sidebar Skip to footer

How To Show An Actitivity Only When An App Widget Is First Created?

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 onCr

Solution 1:

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-providerxmlns: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:

Intentintent= getIntent();
Bundleextras= 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:

Intentintent=newIntent();
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, intent);

finish();

That'll get what you're after.

Solution 2:

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

@OverridepublicvoidonEnabled(Context context) {

    Log.i("INDEX", "WIDGET Enabled");

    AppWidgetManagermgr= AppWidgetManager.getInstance(context); 
    RemoteViewsdefaultViews=newRemoteViews(context.getPackageName(), R.layout.widget_restart); 
    Intentidefault=newIntent(context, MainActivity.class);
    idefault.putExtra("widget", "1");
    PendingIntentdefaultpendingIntent= PendingIntent.getActivity(context, 0, idefault, 0);
    defaultViews.setOnClickPendingIntent(R.id.headWidget, defaultpendingIntent);
    ComponentNamecomp=newComponentName(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 :)

Post a Comment for "How To Show An Actitivity Only When An App Widget Is First Created?"