如何分享活动和窗口小部件之间的数据?部件、窗口、数据

2023-09-06 05:42:34 作者:Super丿潮流盛典

我读了HelloWidget的教程和开发指南应用程序的窗口小部件。然后,我知道如何创建一个小部件,其中包含按钮或文本什么的。

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。但经过我acitivy编辑文本,请问小部件读它?

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

推荐答案

您需要做的是注册自定义的意图,例如ACTION_TEXT_CHANGED在AppWidgetProvider像这样的例子:

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";

在此,你需要在你的Andr​​oidManifest.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>

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

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.

我希望它能帮助。