通知getIntent()。getExtras()获取相同的包

时间:2011-02-19 07:12:15

标签: android

我遇到的问题是每次调用sendAffimationNotice()两次传递一个唯一的aff_id(通过打印“put”+ aff_id确认)。

这会打印'putting 1',然后打印'putting 2'

手机现在有2个通知。虽然点击它们时它们都在intents活动的onCreate方法中都有相同的ID。

两次都打印“ID为:1”,即使两个通知都是唯一的。

public class PossAffNotification{

private static int notif_ID = 1;
private static NotificationManager notificationManager;
private static Notification note;
private static PendingIntent contentIntent;

public static void sendAffimationNotice(Context ctx, String title,String contentText,int aff_id){

    notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
    note = new Notification(android.R.drawable.btn_star_big_on, contentText, System.currentTimeMillis() );

    note.defaults |= Notification.DEFAULT_SOUND;
    note.defaults |= Notification.DEFAULT_VIBRATE;
    note.defaults |= Notification.FLAG_AUTO_CANCEL;
    note.flags |= Notification.FLAG_AUTO_CANCEL;

    Intent notificationIntent = new Intent(ctx, com.mindfsck.PossAff.MainActivity.class);
    notificationIntent.putExtra("aff_id",aff_id);
    System.out.println("putting " + aff_id);

    notificationIntent.setAction("com.mindfsck.PossAff.intent.action.aff");

    notificationIntent = notificationIntent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

    contentIntent = PendingIntent.getActivity(ctx, 0, notificationIntent, 0);

    note.setLatestEventInfo(ctx, title, contentText, contentIntent);

    notificationManager.notify(notif_ID,note);

    notif_ID += 1;
}

   };

    public class MainActivity extends Activity{
        @Override
        public void onCreate(Bundle savedInstanceState){

            super.onCreate(savedInstanceState);

            Intent serviceIntent = new Intent(this,PAService.class);
            this.startService(serviceIntent);

            Bundle extras = getIntent().getExtras();
            if(extras !=null) {
                Toast.makeText(getApplicationContext(), "ID is: " + extras.getInt("aff_id"),
                Toast.LENGTH_SHORT).show();
            }
        }
}

3 个答案:

答案 0 :(得分:1)

您的Intent在所有非额外参数(例如,操作)上都相同。因此,您从PendingIntent来电中获得相同的getActivity(),因为每个不同的PendingIntent只有一个Intent。您需要在第二个Intent中更改某些内容(超出额外内容),例如不同的操作字符串。

答案 1 :(得分:0)

这个问题来自这一行:

contentIntent = PendingIntent.getActivity(ctx, 0, notificationIntent, 0);

最后一个参数不应为0,应该是PendingIntent.FLAG_CANCEL_CURRENT

contentIntent = PendingIntent.getActivity(ctx, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);

否则在notificationIntent中您将始终收到相同的数据

答案 2 :(得分:-1)

我的这篇文章可能对此有所帮助:“A pitfal in PendingIntent

这个问题基本上来自这样一个事实,即系统不会假设只是因为我们将新的Intent对象传递给挂起的intent,我们希望这个新的intent对象被传递并且只保留旧的(初始)挂起的intent活着。

要获得所需的语义,我们需要传递一个标志来告诉系统:

PendingIntent pintent = 
   PendingIntent.getActivity(context,0,intent,PendingIntent.FLAG_CANCEL_CURRENT);