I have a simple widget with 2 buttons. Clicking on any widget button should open the same activity, but with a different parameter. Everything works good: clicking button 1 opens an activity and passes param 1, clicking button 2 opens an activity and passes param 2. I check the parameter passed with:
getIntent().getStringExtra("mode")
The problem begins when I press Android Home button to close the app - after that the app flow doesn't recognize what button was pressed. But if I close the app with Back button - everything is good.
My guess is that after pressing Home and clicking one of the widget buttons, the most recent intent is used instead of using the intent that corresponds to the button clicked.
What I've tried so far:
Here's onUpdate code:
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_home);
Intent intent1 = new Intent(context, MainActivity.class);
intent1.putExtra("mode", "1");
Intent intent2 = new Intent(context, MainActivity.class);
intent2.putExtra("mode", "2");
PendingIntent pendingIntent1 = PendingIntent.getActivity(context, 0,
intent1, PendingIntent.FLAG_CANCEL_CURRENT);
PendingIntent pendingIntent2 = PendingIntent.getActivity(context, 1,
intent2, PendingIntent.FLAG_CANCEL_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.button1, pendingIntent1);
remoteViews.setOnClickPendingIntent(R.id.button2, pendingIntent2);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}
Manifest:
<receiver
android:name="com.testwidgetbuttons.HomeWidgetProvider"
android:icon="@drawable/ic_launcher"
android:label="Example Widget" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/widget" />
</receiver>
Widget xml:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:initialLayout="@layout/widget_home"
android:minHeight="72dp"
android:minWidth="146dp"
android:updatePeriodMillis="1800000" >
</appwidget-provider>
Please advise. Thanks.
Since your activity is still running when you press the home button, the intent to launch MainActivity is isn't being read through your activity's onCreate()
method.
As described here, when passing a new intent into an existing activity instance, instead use Activity.onNewIntent()
.
If you'd instead like to have any previous instance be finished and recreated, you may want to specify the FLAG_ACTIVITY_CLEAR_TOP launch flag into your intents.