分享

揭秘Android Widget的bug之Widget与Activity之间的数据传递 - water的日志 - 网易博客

 techres 2010-11-22

揭秘Android Widget的bug之Widget与Activity之间的数据传递

Android 研究 2010-07-30 15:45:19 阅读7 评论0   字号: 订阅

在我们创建Widget后, 需要通过点击Widget再次进入Activity,这时候往往需要传递数据,我们可以通过设置 PendingIntent的方式在Intent中存放数据达到目的。 但是Intent的putExtra()方法无法携带数据,而只能用setData()方法传递,这在之前的外包项目中遇到过,今天在修改 EasyNote时再次遇到,所以觉得有必要分享出来。 具体代码如下:

 
public class NoteWidget extends AppWidgetProvider {

private String TAG = NoteWidget.class.getSimpleName();
private NotePadDbAdapter mAdapter;

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
for (int i = 0; i < appWidgetIds.length; i++) {
Log.i(TAG, "onUpdate id=" + appWidgetIds[i]);
int noteId = setting.getNoteWidgetId(appWidgetIds[i]);
if(noteId != -1){
Note note = mAdapter.fetchNoteById(noteId);
Log.i(TAG, "onUpdate noteId=" + noteId);
if (null != note) {
Log.i(TAG, "onUpdate note title=" + note.title);
updateWidget(appWidgetManager,context, appWidgetIds[i], note);
}
}
}

}

@Override
public void onReceive(Context context, Intent intent) {

}


private void updateWidget(AppWidgetManager appWidgetManager, Context context, int appWidgetId, Note note) {
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget);
views.setTextViewText(R.id.note_body, note.body);
views.setTextColor(R.id.note_body, note.textColor);
views.setTextViewText(R.id.note_title, note.title);
views.setTextColor(R.id.note_title, note.textColor);
views.setImageViewResource(R.id.note_bg, MainActivity.s_note_bg[note.textBackground]);


Intent intent = new Intent(context,ViewNoteActivity.class);
'''//用setData()方法可以传递数据,但是用putExtra()却不可以达到传递数据的目的'''
Uri dataUri = Uri.parse(String.valueOf(note.id));
intent.setData(dataUri);
//intent.putExtra(ViewNoteActivity.EXTRA_NOTE_ID, note.id);
PendingIntent mPendingIntent = PendingIntent.getActivity(context, 0,
intent, 0);
views.setOnClickPendingIntent(R.id.note_item, mPendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}



@Override
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
}

}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多