Skip to content Skip to sidebar Skip to footer

How To Share Data Between Activity And Widget?

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. But what I really want to do is making it

Solution 1:

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

publicstaticfinalStringACTION_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:

<receiverandroid:name=".DrinkWaterAppWidgetProvider"><intent-filter><actionandroid:name="android.appwidget.action.APPWIDGET_UPDATE" /><actionandroid:name="yourpackage.TEXT_CHANGED" /></intent-filter><meta-dataandroid: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:

@OverridepublicvoidonReceive(Context context, Intent intent) {
    super.onReceive(context, intent);
    if (intent.getAction().equals(ACTION_TEXT_CHANGED)) {
        // handle intent hereString 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:

Intentintent=newIntent(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.

Solution 2:

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...

RemoteViewsviews= 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.

Post a Comment for "How To Share Data Between Activity And Widget?"