How to show an actitivity only when an app widget is first created?

后端 未结 2 1646
野趣味
野趣味 2021-01-16 04:43

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.

AppWidge

2条回答
  •  时光取名叫无心
    2021-01-16 04:43

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

提交回复
热议问题