java Android具有多个通知和多个意图
我有一个相当简单的应用程序,它接受用户的输入,然后将其设置为通知。用户可以创建任意数量的通知。我希望用户单击通知并进入名为ResultActivity
的新活动ResultActivity
依次从通知意图中读入putExtras
,并将其显示给用户。下面的代码允许我做几乎所有我想做的事情,除了任何时候按下通知,我都会收到上次创建的通知的putExtra
Intent notificationIntent = new Intent(ctx, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(ctx, i,notificationIntent,PendingIntent.FLAG_CANCEL_CURRENT);
NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
Resources res = ctx.getResources();
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx);
builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(res,R.drawable.ic_launcher))
.setTicker("Remember to " + text.getText())
.setWhen(System.currentTimeMillis()).setAutoCancel(true)
.setContentTitle(text.getText());
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, ResultActivity.class);
String pass = text.getText().toString();
resultIntent.putExtra("title", pass);
resultIntent.putExtra("uid", i);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
new Uri.Builder().scheme("data").appendQueryParameter("text", "my text").build();
builder.setContentIntent(resultPendingIntent);
Notification n = builder.build();
n.flags = Notification.FLAG_NO_CLEAR;
nm.notify(i++, n);
text.setText(null);
打开应用程序
输入“一”
点击ok
已发送通知
打开应用程序
输入“两个”
点击ok
已发送通知
现在您有两个通知。一个说“一”,一个说“二”。如果你点击通知“2”,它会带你进入一个显示“2”的屏幕。太好了
如果你点击通知“一”,它会带你进入一个显示“二”的屏幕。坏了
结果性。爪哇
public class ResultActivity extends Activity {
String title = null;
TextView text;
int i=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
text = (TextView) findViewById(R.id.textView1);
title = getIntent().getStringExtra("title");
i = getIntent().getIntExtra("uid", 0);
text.setText(title);
}
# 1 楼答案
使用一些随机请求代码来分隔两个通知
# 2 楼答案
我知道这是很久以前的事了,但我觉得答案并没有说明代码中的问题。 所以问题就在这里
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
因此,您可以从stackbuilder中创建一个PendingEvent,其标志为update_current。如果你看一下当前的标志,它会说
因此,在您的用例中,您从stackbuilder创建了两个相同的PendingEvents,第二个意图覆盖第一个。实际上,你从来没有创建过第二个,你只是更新了第一个的额外内容
所以不幸的是,您的用例没有可用的标志,但是有一个很好的解决方法。您可以使用resultIntent的setAction并放置一个随机字符串或对应用程序有意义的字符串
例如
resultIntent.setAction("dummy_action_" + notification.id);
这将使您的ResultEnt足够独特,以便PendingEvent将创建它,而不是更新以前的结果
# 3 楼答案
您创建了多个混合的意图。我清理了代码(但没有测试)
# 4 楼答案
设置不同的
requestCode
帮助我创建和更新当前意图