开发者

Updating extras in an intent in app Widget in Android

开发者 https://www.devze.com 2023-01-30 22:14 出处:网络
My code: @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

My code:

@Override
 public void onUpdate(Context context, AppWidgetManager appWidgetManager,
   int[] appWidgetIds) {
  Intent active = new Intent(context, DialerWidget.class);
  active.setAction(ACTION_WIDGET_RECEIVER);
  active.putExtra("com.anirudha.android.appwidget.Number", currentNumber);
  PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context,
    0, active, 0);
  views.setOnClickPendingIntent(R.id.one,
    actionPendingIntent);
  views.setTextViewText(R.id.number, currentNumber);
  appWidgetManager.updateAppWidget(appWidgetIds, views);
 }

        @Override
        public void onReceive(Context context, Intent intent) {
  if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
   currentNumber = intent.getStringExtra("Number");
   currentNumber += "1";  
   Intent active = new Intent(context, DialerWidget.class);
   active.setAction(ACTION_WIDGET_RECEIVER);
   active.putExtra("com.anirudha.android.appwidget.Number", CurrentNumber);
   active.putExtra("com.anirudha.android.appwidget.Key", "1");
   PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context,
      0, active, 0);
   views.setOnClickPendingIntent(R.id.one,
      actionPendingIntent);

   views.setTextViewText(R.id.number, currentNumber);
   ComponentName cn = new ComponentName(context.getPackageName(),
      DialerWidget.class.getName());
   AppWidgetManager appWidgetManager = AppWidgetM开发者_StackOverflow中文版anager.getInstance(context);
   appWidgetManager.updateAppWidget(cn, views);

   Toast.makeText(context, currentNumber, Toast.LENGTH_SHORT).show();   
  }
   super.onReceive(context, intent);
 }

So, basically i want to change the extras i should receive with the Intent. But whenever the button is pressed i receive the same value with the Intent. I'm new to android development. Any help would be appreciated. Thanks


If you want to update an existing pending intent, you have to use the FLAG_UPDATE_CURRENT flag when you create it.

PendingIntent actionPendingIntent = 
     PendingIntent.getBroadcast(context, 0, active, PendingIntent.FLAG_UPDATE_CURRENT);


What type is currentNumber? It's not shown but from the code I guess it's an int. You are putting it into the extra as an int, but you are reading it out as a string. The string will always we empty because there is no string extra with that name so currentnumber will also be 0, then increased by 1, so always be 1.

Also you are writing it with "com.anirudha.android.appwidget.Number" but reading with "Number". This must be the same key for writing and reading.

Solution: use getIntExtra()

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号