【问题标题】:How to remove notifications when touched? [duplicate]触摸时如何删除通知? [复制]
【发布时间】:2015-06-10 03:37:07
【问题描述】:

我正在尝试开发一个在您退出时会发出通知的应用程序。但我希望当您触摸通知并重新打开应用程序时,通知会消失。我该怎么办?

我的代码:

public class MainActivity extends Activity {

    NotificationCompat.Builder mBuilder;

    @SuppressWarnings("deprecation")    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main_land);
        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);


        mBuilder =
                new NotificationCompat.Builder(MainActivity.this)
                    .setSmallIcon(android.R.drawable.stat_sys_warning)
                    .setContentTitle("Mensaje de Alerta")
                    .setContentText("Ejemplo de notificación.")
                    .setContentInfo("4")
                    .setTicker("Alerta!");

        }


    public void salir(View view) {

        finish();
        Intent notIntent =
                new Intent(MainActivity.this, MainActivity.class);

            PendingIntent contIntent =
                PendingIntent.getActivity(
                    MainActivity.this, 0, notIntent, 0);

            mBuilder.setContentIntent(contIntent);
            NotificationManager mNotificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

                mNotificationManager.notify("NOTIFICATION", 0, mBuilder.build());

    }

}

此代码仅发出通知并再次打开应用程序。

【问题讨论】:

    标签: android notifications android-notifications


    【解决方案1】:

    使用标志

     notification.flags = Notification.FLAG_AUTO_CANCEL;
    

    使用通知生成器

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setAutoCancel(true);
    

    使用通知管理器

    notificationManager.cancel(NOTIFICATION_ID);
    

    适用于 API 级别 18 及以上

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    public class MyNotificationListenerService extends NotificationListenerService {...}
    ...
    
    private void clearNotificationExample(StatusBarNotification sbn) {
        myNotificationListenerService.cancelNotification(sbn.getPackageName(), sbn.getTag(), sbn.getId());
    }
    

    【讨论】:

    • 但在我的代码中.. 我把这段代码放在哪里?
    • 尝试在 NotificationCompat.Builder 中设置标志
    猜你喜欢
    • 2019-11-17
    • 2019-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-19
    • 2022-01-17
    • 2018-06-22
    相关资源
    最近更新 更多