mercredi 6 mai 2015

Android widget send Data to onRecive via intent

I'm creating an android widget that by clicking, every instance of the widget will go to a different url.

I'm having a problem sending the url from the 'onUpdate' to the 'onReceive' method.

The onUpdate code:

 List<String> urls = Arrays.asList("google.com", "yahoo.com", "bing.com", "msn.com");

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

    int cnt = 0;

    // Get all ids
    ComponentName thisWidget = new ComponentName(context,MyWidgetProvider.class);
    int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
    for (int widgetId : allWidgetIds) {
        // create some random data

        RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.widget_layout);
        Log.w("WidgetExample", urls.get(cnt));
        // Set the text
        remoteViews.setTextViewText(R.id.urlData, urls.get(cnt));

        // Register an onClickListener
        Intent intent = new Intent(context, MyWidgetProvider.class);

        intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
        intent.putExtra("url",urls.get(cnt));

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context,0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.open, pendingIntent);
        appWidgetManager.updateAppWidget(widgetId, remoteViews);

        cnt++;
    }
}

The onReceive code:

 @Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);

    String TAG = "onReceive";

        Bundle extras = intent.getExtras();
        if(extras!=null) {
            String url = extras.getString("url");
            Log.d(TAG, "url is : "+url);
        }else {
            Log.d(TAG, "no url");
        }
}

The problem is that i allwas get the same url (the last one in the list - 'msn.com').

Thank's allot

Avi

Aucun commentaire:

Enregistrer un commentaire