How to launch activity from android home screen wi

2019-01-19 19:03发布

问题:

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 press setting up an intent filter in the manifest.

However, I cannot for the life of me figure out how to launch an activity when the button is pressed. Basically, here's the code i have:

 @Override 
 public void onReceive(Context context, Intent intent) 
 { 
      super.onReceive(context, intent); 
      if(intent.getAction().equals("com.bic.search.searchWidget.CLICK")) 
      { 
           Toast.makeText(context, "It works!!", Toast.LENGTH_SHORT).show(); 
      } 
 } 

What I really want to do, though, is start a new activity, not display a toast message. I know it has something to do with pending intents, but I can't figure out how to get that to work.

Any help and sample code would be appreciated. Thanks a ton to whoever answers this!

回答1:

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.



回答2:

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!