ฉันMainActicity จะเริ่มต้นRefreshServiceด้วยการIntentที่มีความพิเศษที่เรียกว่าbooleanisNextWeek
ของฉันRefreshServiceทำให้Notificationซึ่งเริ่มต้นของฉันMainActivityเมื่อผู้ใช้คลิกที่มัน
ลักษณะเช่นนี้:
Log.d("Refresh", "RefreshService got: isNextWeek: " + String.valueOf(isNextWeek));
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.putExtra(MainActivity.IS_NEXT_WEEK, isNextWeek);
Log.d("Refresh", "RefreshService put in Intent: isNextWeek: " + String.valueOf(notificationIntent.getBooleanExtra(MainActivity.IS_NEXT_WEEK,false)));
pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
builder = new NotificationCompat.Builder(this).setContentTitle("Title").setContentText("ContentText").setSmallIcon(R.drawable.ic_notification).setContentIntent(pendingIntent);
notification = builder.build();
// Hide the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(NOTIFICATION_REFRESH, notification);
ในฐานะที่คุณสามารถเห็นnotificationIntentควรมีความbooleanพิเศษIS_NEXT_WEEKที่มีค่าของที่จะใส่ในisNextWeekPendingIntent
เมื่อฉันคลิกตอนนี้Notificationฉันจะได้รับfalseเป็นค่าของisNextWeek
นี่คือวิธีที่ฉันได้รับค่าในMainActivity:
isNextWeek = getIntent().getBooleanExtra(IS_NEXT_WEEK, false);
เข้าสู่ระบบ:
08-04 00:19:32.500 13367-13367/de.MayerhoferSimon.Vertretungsplan D/Refresh: MainActivity sent: isNextWeek: true
08-04 00:19:32.510 13367-13573/de.MayerhoferSimon.Vertretungsplan D/Refresh: RefreshService got: isNextWeek: true
08-04 00:19:32.510 13367-13573/de.MayerhoferSimon.Vertretungsplan D/Refresh: RefreshService put in Intent: isNextWeek: true
08-04 00:19:41.990 13367-13367/de.MayerhoferSimon.Vertretungsplan D/Refresh: MainActivity.onCreate got: isNextWeek: false
เมื่อฉันโดยตรงเริ่มต้นMainActivityด้วยการIntentที่มีìsNextValue`เช่นนี้:
Intent i = new Intent(this, MainActivity.class);
i.putExtra(IS_NEXT_WEEK, isNextWeek);
finish();
startActivity(i);
ทุกอย่างทำงานได้ดีและฉันได้รับtrueเมื่อเป็นisNextWeektrue
ฉันทำอะไรผิดที่มีfalseค่าเสมอ?
UPDATE
วิธีนี้ช่วยแก้ปัญหาได้: https://stackoverflow.com/a/18049676/2180161
อ้างถึง:
ความสงสัยของฉันคือเนื่องจากสิ่งเดียวที่เปลี่ยนแปลงใน Intent คือความพิเศษ
PendingIntent.getActivity(...)วิธีการของโรงงานจึงใช้เจตนาเดิมอีกครั้งเป็นการเพิ่มประสิทธิภาพใน RefreshService ให้ลอง:
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);ดู:
http://developer.android.com/reference/android/app/PendingIntent.html#FLAG_CANCEL_CURRENT
อัปเดต 2
ดูคำตอบด้านล่างPendingIntent.FLAG_UPDATE_CURRENTว่าทำไมมันจะดีกว่าการใช้งาน