我正在创建一个应用程序,必须显示多个通知。我一直在寻找的信息,我在课堂上使用此代码:多个通知,并只显示第一个Android
Notification noti = new NotificationCompat.Builder(this)
我可以显示栏上有多个通知,但问题是,当我点击它只显示第一个。我认为它是因为待决意图获得的id始终相同,但我发送了另一个。
通知活动:当我点击按钮时显示新通知。
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.View;
public class NotificationActivity extends Activity {
int notificationID = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_example);
}
public void onClick(View v){
displayNotification();
}
protected void displayNotification(){
Intent i = new Intent(this, NotificationView.class);
i.putExtra("notificationID", notificationID);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, 0);
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
CharSequence ticker ="Display";
CharSequence contentTitle = "Title";
CharSequence contentText = "Description";
Notification noti = new NotificationCompat.Builder(this)
.setContentIntent(pendingIntent)
.setTicker(ticker)
.setContentTitle(contentTitle)
.setContentText(contentText)
.setSmallIcon(R.drawable.ic_launcher)
.addAction(R.drawable.ic_launcher, ticker, pendingIntent)
.setVibrate(new long[] {100, 250, 100, 500})
.build();
Log.d("Send Notification", "id: "+notificationID);
nm.notify(notificationID, noti);
notificationID++;
}
}
正如你可以看到我增加notificationID每次我点击按钮发送一个不同的ID。
通知查看:显示通知的ID。
import android.app.Activity;
import android.app.NotificationManager;
import android.os.Bundle;
import android.widget.TextView;
public class NotificationView extends Activity {
TextView txt;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.notification);
txt= (TextView) findViewById(R.id.txt1);
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
txt.setText("Notification ID: "+getIntent().getExtras().getInt("notificationID"));
// Cancel notification
nm.cancel(getIntent().getExtras().getInt("notificationID"));
}
}
这里只显示通知的ID,但它总是1.
大约发生了什么你知道吗?我正在2.3设备上测试它。
谢谢大家。
你能解释一下吗?我不明白你想告诉我什么。 --------------------- 好的,它的工作:)谢谢。 – Fernando
此代码创建不同的通知但不覆盖 – AnilPatel
基本上给每个pendingintent一个唯一的编号在这里。在notify()中使用该数字之后,它会为接下来的通知递增。 –