【问题标题】:How to launch activity from android home screen widget如何从 android 主屏幕小部件启动活动
【发布时间】:2011-02-11 23:36:14
【问题描述】:

我正在拼命思考如何实现主屏幕小部件。现在,我(终于)能够在我的小部件上获得一个按钮来响应按钮按下,在清单中设置一个意图过滤器。

但是,我终其一生都无法弄清楚按下按钮时如何启动活动。基本上,这是我的代码:

 @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(); 
      } 
 } 

不过,我真正想做的是开始一项新活动,而不是显示敬酒消息。我知道这与未决意图有关,但我不知道如何让它发挥作用。

任何帮助和示例代码将不胜感激。非常感谢回答这个问题的人!

【问题讨论】:

    标签: android android-activity android-widget android-appwidget


    【解决方案1】:

    好吧,您的应用小部件应该已经有一个您绑定到按钮的PendingIntent。而不是触发BroadcastReceiverPendingIntent,而是启动ActivityPendingIntent

    【讨论】:

    • 链接坏了,能补一下吗?
    • @Joel:抱歉,我目前没有演示这个的项目。
    【解决方案2】:

    您可以使用此代码来解决您的问题。

    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;
            }
        }
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-20
      • 1970-01-01
      • 2011-03-22
      • 2014-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多