Android Notification未在AddAction上关闭

时间:2016-12-03 22:50:42

标签: android android-intent notifications android-pendingintent

我使用了Stack Overflow上的一些答案,但是它们没有用。但基本上,我需要通知我做两件事。一,我需要它在单击通知本身时再次打开应用程序,我需要它在单击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();
}

2 个答案:

答案 0 :(得分:0)

您拥有以下代码:

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

将标记为“已完成”的操作设置为startActivity(),该closeIntent会启动您的应用。它完全符合它的要求。

用户已经知道如何在不执行任何操作的情况下滑动通知以将其删除。为什么你还要在通知中添加一个额外的操作按钮才能完全实现?对我来说似乎有点过分了。

如果你想要这个,你可以尝试在动作上使用null PendingIntent,因为基本上你不想在用户点击按钮时发生任何事情:

builder.addAction(R.drawable.ic_action_name, "Done",
        null); //Action for the closer

答案 1 :(得分:0)

只需添加builder.autoCancel(true);

即可

这将解决您的问题。