Android主屏幕小部件没有在配置活动中获得appWidgetId

时间:2011-10-07 22:16:05

标签: android android-widget widget android-appwidget

我有一个小部件,我想在屏幕上添加多个小部件,所以当我在appWidgetId的主屏幕上点击它时,我必须控制我正在配置的小部件。

我正在关注android.com中的文档,但是当我在主屏幕上点击它时,我没有收到appWidgetId。

我的代码:

// MyWidgetClass

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {
    Log.i(TAG, CLASS_NAME + " onUpdate");
    for (int appWidgetId : appWidgetIds) {
        updateAppWidget(context, appWidgetManager, appWidgetId);
    }
}

public static void updateAppWidget(Context context,
        AppWidgetManager appWidgetManager, int appWidgetId) {
    Log.d(TAG, CLASS_NAME + " updateAppWidget --- " + appWidgetId);
    if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {

        Intent settingsIntent = new Intent(context,
                Widget1x1SettingsActivity.class);
        settingsIntent
                .setAction(android.appwidget.AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
        //settingsIntent.putExtra("WIDGET_ID", appWidgetId);
        PendingIntent settingsPendingIntent = PendingIntent.getActivity(
                context, 0, settingsIntent, 0);

        RemoteViews remoteViews = null;

        int layout = R.layout.widget_1x1;
        remoteViews = new RemoteViews(context.getPackageName(), layout);
        // Do something ...

            remoteViews.setOnClickPendingIntent(R.id.widget,
                    settingsPendingIntent);

            ComponentName thisWidget = new ComponentName(context,
                    MyWidgetClass.class);
            appWidgetManager.updateAppWidget(thisWidget, remoteViews);

    }
}

//设置类

@Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, CLASS_NAME + " :: onCreate >>");
        super.onCreate(savedInstanceState);

        mContext = getApplicationContext();

        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            //**//Here appWidgetId is 0 when I click on home screen widget**
        }
....
}

当我点击“确定”按钮完成配置活动时:

AppWidgetManager appWidgetManager = AppWidgetManager
                    .getInstance(getApplicationContext());
            MyWidgetClass.updateAppWidget(getApplicationContext(),
                    appWidgetManager, appWidgetId);
            Intent resultValue = new Intent();
            resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    appWidgetId);
            Log.d(TAG, CLASS_NAME + " Putting in RESULT resultValue extras: " + resultValue.getExtras() + " getInt(): " + resultValue.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID)); // it prints correct
            setResult(RESULT_OK, resultValue);
            finish();

我不粘贴任何xml文件,因为我认为它们没问题。

提前致谢, SergiBC

0 个答案:

没有答案