如何在活动和小部件之间共享数据?

编程入门 行业动态 更新时间:2024-10-24 18:26:58
本文介绍了如何在活动和小部件之间共享数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我阅读了 hellowidget 教程和开发指南的 App Widgets.然后我知道如何创建一个包含按钮或文本或其他内容的小部件.

I read the hellowidget tutorial and Dev Guide' App Widgets. Then I know how to create a widget which contains button or text or something.

但我真正想做的是让它与我的应用交互.例如,我想创建一个具有文本视图的小部件,当我单击它时,它会向我的活动发送一个 PendingIntent,我可以在其中编辑文本.

But what I really want to do is making it interact with my app. For example, I want to create a widget that has a text view, and when I click it, it sends a PendingIntent to my activity in which I can edit the text.

我可以执行发送 PendingIntent"步骤.但是我在活动中编辑文本后,小部件如何读取它?

I can do the step "sends a PendingIntent". But after I edit text in acitivy, how does the widget read it?

推荐答案

你需要做的是注册一个自定义的intent,例如在你的AppWidgetProvider中注册一个ACTION_TEXT_CHANGED,例如:

What you need to do is register a custom intent, for example ACTION_TEXT_CHANGED in your AppWidgetProvider like this for example:

public static final String ACTION_TEXT_CHANGED = "yourpackage.TEXT_CHANGED";

在此之后,您需要在您的 AndroidManifest.xml 中注册您希望在接收者标签的意图过滤器部分接收此意图,如下所示:

After this, you need to register in your AndroidManifest.xml that you want to receive this intents in the intent-filter section of your receiver tag like this:

<receiver android:name=".DrinkWaterAppWidgetProvider"> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> <action android:name="yourpackage.TEXT_CHANGED" /> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/appwidget_info" /> </receiver>

然后你必须在你的 AppWidgetProvider 中扩展 onReceive 方法,并确保你处理你的意图是这样的:

Then you have to extend the onReceive method in your AppWidgetProvider and make sure that you're handling your intent like this:

@Override public void onReceive(Context context, Intent intent) { super.onReceive(context, intent); if (intent.getAction().equals(ACTION_TEXT_CHANGED)) { // handle intent here String s = intent.getStringExtra("NewString"); } }

以上所有设置完成后,您只需要在文本更改后在活动中广播意图,如下所示:

After all the above is set up, you just need to broadcast the intent in your activity after the text has changed like this:

Intent intent = new Intent(YourAppWidgetProvider.ACTION_TEXT_CHANGED); intent.putExtra("NewString", textView.getText().toString()); getApplicationContext().sendBroadcast(intent);

其中NewString"应更改为您为字符串提供的名称.

Where "NewString" should be changed to the name you to give the the string.

希望对你有帮助.

更多推荐

如何在活动和小部件之间共享数据?

本文发布于:2023-08-01 12:27:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1268324.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:部件   数据   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!