How to share data between activity and widget?

[亡魂溺海] 提交于 2019-12-04 05:54:53

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

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>

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

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

I hope it helps.

You have to use the RemoteViews class to do it. Create an instance of RemoteViews class inside your AppWidgetProvider's onRefresh method and use the methods in it...

RemoteViews views = RemoteViews(packageName, layoutId);
views.setOnClickPendingIntent(viewId, pendingIntent);

Note that RemoteViews is limited in functionality when compared with the standard app views. But, you can achieve what you wanted to do with what they provide.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!