Как создать несколько предупреждений о статусе в android
Мне нужно создать несколько уведомлений о статусе. Когда я вытаскиваю строку состояния, в качестве списка должны отображаться несколько значков уведомлений. Каждый значок уведомления должен отображать отдельные данные для отображения на следующей странице. Как я могу это сделать?
Мой код:
public class SimpleNotification extends Activity {
private NotificationManager mNotificationManager;
private int SIMPLE_NOTFICATION_ID;
String str="Hai";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
final Notification notifyDetails = new Notification(R.drawable.android,"New Alert, Click Me!",System.currentTimeMillis());
Button start = (Button)findViewById(R.id.notifyButton);
Button cancel = (Button)findViewById(R.id.cancelButton);
start.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Context context = getApplicationContext();
CharSequence contentTitle = "Notification Details...";
CharSequence contentText = "Browse Android Official Site by clicking me";
Intent notifyIntent = new Intent(SimpleNotification.this,
sub.class);
Bundle bundle = new Bundle();
bundle.putString("welcome",str);
notifyIntent.putExtras(bundle);
PendingIntent intent =
PendingIntent.getActivity(SimpleNotification.this, 0,
notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
notifyDetails.setLatestEventInfo(context, contentTitle, contentText, intent);
mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
}
});
Здесь я сделал для одного уведомления, но мне нужно создать несколько уведомлений о том, что каждое уведомление должно показывать все данные.
Ответы
Ответ 1
Вам необходимо передать уникальный идентификатор каждому уведомлению. После того как вы нажали на уведомление, вы используете этот идентификатор, чтобы удалить его.
public class SimpleNotification extends Activity {
private NotificationManager mNotificationManager;
private int SIMPLE_NOTFICATION_ID_A = 0;
private int SIMPLE_NOTFICATION_ID_B = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Button start = (Button) findViewById(R.id.start_button);
start.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// display A
displayNotification("Extra for A", "This is A", "Some text for activity A", MyActivityA.class, SIMPLE_NOTFICATION_ID_A);
// display B
displayNotification("Extra for B", "This is B", "Some text for activity B", MyActivityB.class, SIMPLE_NOTFICATION_ID_B);
}
});
}
private void displayNotification(String extra, String contentTitle, String contentText, Class<?> cls, int id) {
Notification notifyDetails = new Notification(R.drawable.icon, "New Alert!", System.currentTimeMillis());
Intent intent = new Intent(this, cls);
intent.putExtra("extra", extra);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), id, intent, PendingIntent.FLAG_ONE_SHOT);
notifyDetails.setLatestEventInfo(getApplicationContext(), contentTitle, contentText, contentIntent);
mNotificationManager.notify(id, notifyDetails);
}
}
MyActivityA - in onCreate()
...
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.cancel(SIMPLE_NOTFICATION_ID_A);
...
Ответ 2
Просто используйте разные идентификаторы на mNotificationManager.notify(ID, notifyDetails);
Если вы повторно используете идентификатор, он не добавит новый, вместо этого будет обновлен старый.
Вот руководство по использованию notifications.
Ответ 3
вам нужно указать идентификатор идентификатора, потому что все время не решение заключается в том, что вы должны использовать концепцию чисел ramdom
Random random = new Random();
int randomNumber = random.nextInt(9999 - 1000) + 1000;
notificationManager.notify(randomNumber, notification);
Ответ 4
В этом примере показано, как создать несколько уведомлений
Ответ 5
Если вы хотите показывать разные данные для каждого уведомления. Используйте флаг FLAG_UPDATE_CURRENT
в ожидающем Intent
.
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Он обновляет данные для каждого уведомления без необходимости его повторного создания каждый раз.