我使用了一些在堆栈溢出上找到的答案,但它们没有起作用。但是基本上,我需要通知才能做两件事。首先,我需要它在单击通知本身时再次打开应用程序,并且我需要在单击AddAction时关闭通知。
单击应用程序时,通知将打开该应用程序,这是正确的,但是当我单击addAction("完成")时,它会执行同样的事情。与通知本身一样,它没有关闭通知的操作,而是打开应用程序。可能出了什么问题?
public void onInput(MaterialDialog dialog, CharSequence input) {
//notification body
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0,
new Intent(getApplicationContext(), MainActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP),
0);
//Rest of Notification
builder.setStyle(new NotificationCompat.BigTextStyle().bigText(input.toString())); //BigText
builder.setOngoing(true); //Make persistent
builder.setContentIntent(pendingIntent); //OnClick for Reopening App
builder.setSmallIcon(R.drawable.ic_note);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
builder.setContentTitle("Remember!");
builder.setContentText(input.toString()); //Get text from dialog input
Intent closeIntent = new Intent(getApplicationContext(), MainActivity.class);
closeIntent.putExtra(getPackageName(), NOTIFICATION_ID);
PendingIntent closeBtn = PendingIntent.getActivity(getApplicationContext(), 0, closeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.addAction(R.drawable.ic_action_name, "Done", closeBtn); //Action for the closer
notificationManager.notify(NOTIFICATION_ID, builder.build());
//toast
Toast.makeText(MainActivity.this, "Done! Reminder has been set. Check your Notification Bar! :)",
Toast.LENGTH_LONG).show();
//Close app when done entering in text
finish();
}
只需添加 builder.autoCancel(true);
这将解决您的问题。
您拥有的此代码:
Intent closeIntent = new Intent(getApplicationContext(), MainActivity.class);
closeIntent.putExtra(getPackageName(), NOTIFICATION_ID);
PendingIntent closeBtn = PendingIntent.getActivity(getApplicationContext(), 0,
closeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.addAction(R.drawable.ic_action_name, "Done",
closeBtn); //Action for the closer
放置一个标有"完成"的操作,将使用closeIntent
调用startActivity()
(启动您的应用程序)。它完全可以做到。
用户已经知道如何在不做任何事情的情况下刷新通知以删除通知。您为什么要在通知中添加附加操作按钮以实现这一目标?对我来说似乎过大。
如果您需要这个,则可以尝试在操作上使用null PendingIntent
,因为基本上您希望当用户单击按钮时什么都不发生:
builder.addAction(R.drawable.ic_action_name, "Done",
null); //Action for the closer