How to launch activity from android home screen widget

前端 未结 2 1580
北恋
北恋 2020-12-11 05:27

I am desperately trying to get my head wrapped around how to implement home screen widgets. Right now, I (finally) was able to get a button on my widget respond to a button

相关标签:
2条回答
  • 2020-12-11 06:01

    Well, your app widget should already have a PendingIntent that you tied to the button. Instead of a PendingIntent that triggers a BroadcastReceiver, have it be a PendingIntent that starts up an Activity.

    0 讨论(0)
  • 2020-12-11 06:14

    You can use this code to solve your problem.

    public class Widget extends AppWidgetProvider {
    
            // ...
    
            public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    
                for(int i = 0; i < appWidgetIds.length; i++){
    
                    RemoteViews widget = new RemoteViews(context.getPackageName(), R.layout.widget);
    
                    Intent startActivityIntent = new Intent(context, myActivity.class);
                    PendingIntent startActivityPendingIntent = PendingIntent.getActivity(context, 0, startActivityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                    widget.setPendingIntentTemplate(R.id.list_view, startActivityPendingIntent);
    
                    appWidgetManager.updateAppWidget(appWidgetIds[i], widget);
    
                    // ...
            }
        }
    
        public class WidgetAdapter implements RemoteViewsService.RemoteViewsFactory {
    
            // ...
    
            @Override
            public RemoteViews getViewAt(int position) {
    
            RemoteViews widgetRow = new RemoteViews(context.getPackageName(), R.layout.widget_row);
    
                Intent fillInIntent = new Intent();
                fillInIntent.putExtra(Widget.EXTRA_LIST_VIEW_ROW_NUMBER, position);
                widgetRow.setOnClickFillInIntent(R.id.list_view_row, fillInIntent);
    
                // ...
    
                return row;
            }
        }
    

    Hope this helps!

    0 讨论(0)
提交回复
热议问题