2012-02-27 54 views
2

我的應用程序具有可顯示可添加到主屏幕的應用程序小部件的開始活動。如何在蜂窩/ ics上打開應用程序部件選取器?

當用戶點擊該應用程序窗口小部件時,應用程序應發送意圖打開窗口小部件列表。

但我找不到任何打開啓動器與小部件列表選擇任何意圖。可能嗎?

回答

2
static final String EXTRA_CUSTOM_WIDGET = "custom_widget"; 
static final String SEARCH_WIDGET = "search_widget"; 
void pickappWidget(){ 
    int appWidgetId = Launcher.this.mAppWidgetHost.allocateAppWidgetId(); 

    Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK); 
    pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); 
    // add the search widget 
    ArrayList<AppWidgetProviderInfo> customInfo = 
      new ArrayList<AppWidgetProviderInfo>(); 
    AppWidgetProviderInfo info = new AppWidgetProviderInfo(); 
    info.provider = new ComponentName(getPackageName(), "XXX.YYY"); 
    info.label = getString(R.string.group_widgets); 
    info.icon = R.drawable.ic_allapps; 
    customInfo.add(info); 
    pickIntent.putParcelableArrayListExtra(
      AppWidgetManager.EXTRA_CUSTOM_INFO, customInfo); 
    ArrayList<Bundle> customExtras = new ArrayList<Bundle>(); 
    Bundle b = new Bundle(); 
    b.putString(EXTRA_CUSTOM_WIDGET, SEARCH_WIDGET); 
    customExtras.add(b); 
    pickIntent.putParcelableArrayListExtra(
      AppWidgetManager.EXTRA_CUSTOM_EXTRAS, customExtras); 
    // start the pick activity 
    startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET); 
} 

,並在你的onActivityResult函數,過程從部件選擇對話框消息retur

protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    mWaitingForResult = false; 
    if (resultCode == RESULT_OK && mAddItemCellInfo != null) { 
     switch (requestCode) { 
      case REQUEST_PICK_APPWIDGET: 
       addAppWidget(data); 
       break; 
     } 
} 


void addAppWidget(Intent data) { 

    int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1); 
    AppWidgetProviderInfo appWidget = mAppWidgetManager.getAppWidgetInfo(appWidgetId); 

    if (appWidget.configure != null) { 
     // Launch over to configure widget, if needed 
     Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE); 
     intent.setComponent(appWidget.configure); 
     intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); 

     startActivityForResult(intent, REQUEST_CREATE_APPWIDGET); 
    } else { 
     // Otherwise just add it 
     onActivityResult(REQUEST_CREATE_APPWIDGET, Activity.RESULT_OK, data); 
    } 
} 
+0

一旦小部件在選擇器選擇,會不會一切發生在它自己的,沒有處理結果?我的意思是應該調用配置活動(在清單中的meta中指定),然後在WidgetProvider被添加到啓動器時WidgetProvider? – 2013-11-24 13:08:42

+0

這看起來不錯。如何獲得對AppWidgetHost(mAppWidgetHost)的引用以分配appWidgetID? – 2013-11-24 13:13:37

+0

也許你的答案是關於將Widgets添加到你自己的AppWidgetHost中?如果是這樣,也許這就是爲什麼答案不被接受 - 因爲它是關於添加到主屏幕,然後我們需要獲得啓動器的AppWidgetHost ....? – 2013-11-24 13:24:31