如何在桌面新增AppWidget

zywncdx發表於2011-08-15
 

   本人第一次寫部落格,為了做個紀念,特此說明...

   今天我來和大家分享下,怎樣將AppWidget新增到介面上。

   將AppWidget放到桌面上,需要兩個必要引數ComponentName,AppWidgetId,拿到ComponentName我們一般直接可以使用ComponentName cn = new ComponentName(packageName, className);即可,這個我就不說的很詳細了,第二步我們就的拿到一個AppWidgetId,怎樣獲得呢?在Launcher工程中就可以通過LauncherAppWidgetHost.java 這個類來得到,它是直接繼承了AppWidget·Host類,使用它的方法mAppWidgetHost.allocateAppWidgetId()可以得到AppWidgetId,好了現在我們拿到了兩個必要的引數,最後我們的通過方法AppWidgetManager.getInstance(this)拿到一個AppWidgetManager例項,並呼叫該例項的方法appWidgetManager.bindAppWidgetId(appWidgetId, cn);將兩個引數繫結到一起即可,當然這還不夠...具體做法參照以下程式碼.

 

ContentResolver cr = this.getContentResolver();
  
  PackageManager packageManager = getPackageManager();
  String packageName = packagename;
        String className = classname;

        boolean hasPackage = true;
        ComponentName cn = new ComponentName(packageName, className);
        try {
            packageManager.getReceiverInfo(cn, 0);
        } catch (Exception e) {
            String[] packages = packageManager.currentToCanonicalPackageNames(
                    new String[] { packageName });
            cn = new ComponentName(packages[0], className);
            try {
                packageManager.getReceiverInfo(cn, 0);
            } catch (Exception e1) {
                hasPackage = false;
            }
        }

        if (hasPackage) {
            int spanX = 2;
            int spanY = 2;
        }
  
  ContentValues values = new ContentValues();
  
   boolean allocatedAppWidgets = false;
         final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);

         try {
             int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
            
             values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
             values.put(Favorites.SPANX, 2);
             values.put(Favorites.SPANY, 2);
             values.put(Favorites.APPWIDGET_ID, appWidgetId);
             values.put(Favorites.CONTAINER, -100);
             values.put(Favorites.CELLX, cellX);
             values.put(Favorites.CELLY, cellY);
             values.put(Favorites.SCREEN, 1);
            
             cr.insert(LauncherSettings.Favorites.CONTENT_URI , values);
            
             allocatedAppWidgets = true;
            
             appWidgetManager.bindAppWidgetId(appWidgetId, cn);
         } catch (RuntimeException ex) {
             Log.e(TAG, "Problem allocating appWidgetId", ex);
         }
        
         return allocatedAppWidgets;
 }

相關文章