我的应用程序有一个堆栈小部件,它当前仅在单击该小部件时启动主要 Activity 。 我想更改此设置,以便为主要 Activity 提供有关被单击的 widgetitem 的信息。 我想要传递的对象实现了 Parcelable 并且可以通过通知中的 Intent 成功传递。但是,当 bundle 在小部件的 Intent 中时,它似乎总是为空。
有什么想法吗?
StackWidgetProvider
// set intent for item click (opens main activity)
Intent viewIntent = new Intent(context, DealPadActivity.class);
viewIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
viewIntent.setData(Uri.parse(viewIntent.toUri(Intent.URI_INTENT_SCHEME)));
PendingIntent viewPendingIntent = PendingIntent.getActivity(context, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT);
rv.setPendingIntentTemplate(R.id.stack_view, viewPendingIntent);
StackWidgetService
public RemoteViews getViewAt(int position) {
RemoteViews rv = new RemoteViews(mContext.getPackageName(), R.layout.stack_widget_item);
if (position < mWidgetItems.size()){
rv.setTextViewText(R.id.stack_widget_title, mWidgetItems.get(position).title);
rv.setTextViewText(R.id.stack_widget_price, mWidgetItems.get(position).price);
rv.setTextViewText(R.id.stack_widget_heat, mWidgetItems.get(position).heat);
Bitmap picture = imageLaoder.getBitmap(mWidgetItems.get(position).imageUrl, true) ;
rv.setImageViewBitmap(R.id.stack_widget_image, picture);
}
Intent fillInIntent = new Intent();
Bundle extras = new Bundle();
extras.putInt(StackWidgetProvider.EXTRA_ITEM, position);
extras.putParcelable("notificationDeal", new Deal(...));
fillInIntent.putExtras(extras);
rv.setOnClickFillInIntent(R.id.stack_widget_layout, fillInIntent);
return rv;
}
主 Activity
Bundle data = queryIntent.getExtras();
if (data!=null){ // check to see if from widget or notification
Deal deal = data.getParcelable("notificationDeal");
if (deal!=null){ // ****ALWAYS NULL FROM WIDGET****
Log.d(this.getClass().getSimpleName(), "going to show passed deal");
onDealSelected(deal);
}
int i = data.getInt("com.bencallis.dealpad.stackwidget.EXTRA_ITEM");
Log.d(this.getClass().getSimpleName(), "pressed widget is: " + i); **WIDGET ITEM POSITION AS EXPECTED **
** 更新**
看来是编码的问题(特别是解码)
E/Parcel: Class not found when unmarshalling: com.bencallis.abc.Deal, e: java.lang.ClassNotFoundException: com.bencallis.abc.Deal
我已将 Deal 类导入到 StackWidgetService 中,并尝试设置类加载器,但这似乎没有帮助。
Deal 寓言在应用程序的主要 Activity 中成功使用,我只是遇到了这个小部件的问题。
交易等级
public Deal(Parcel in) {
in.readParcelable(Deal.class.getClassLoader());
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
...
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Deal createFromParcel(Parcel in) {
return new Deal(in);
}
public Deal[] newArray(int size) {
return new Deal[size];
}
};
最佳答案
您说您已尝试设置类加载器。那应该有效。我不确定您是如何尝试设置类加载器的,因为您没有提供该代码。试试这个:
在 MainActivity
中,插入:
ClassLoader loader = Deal.class.getClassLoader();
queryIntent.setExtrasClassLoader(loader);
在此之前:
Bundle data = queryIntent.getExtras();
关于Android:将对象从集合小部件传递到 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16783305/