我正在尝试开发一个在退出时会发出通知的应用。但是我希望当您触摸通知并重新打开应用程序时,通知会消失。我怎么能这样做?
我的代码:
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());
}
}
此代码仅生成通知,然后再次打开应用程序。
答案 0 :(得分:2)
使用标志
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());
}