Android 取消正在进行的通知

Android 取消正在进行的通知,android,notifications,Android,Notifications,我有一个主类,它通过点击按钮来完美地启动通知,我刚刚创建了另一个按钮来取消正在进行的通知,我应该向下面的代码添加什么来实现这一点 public class CreateNotificationActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.ma

我有一个主类,它通过点击按钮来完美地启动通知,我刚刚创建了另一个按钮来取消正在进行的通知,我应该向下面的代码添加什么来实现这一点

public class CreateNotificationActivity extends Activity {
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 }

public void createNotification(View view) {
// Prepare intent which is triggered if the
// notification is selected
Intent intent = new Intent(CreateNotificationActivity.this, NotificationReceiverActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

// Build notification
// Actions are just fake
Notification noti = new Notification.Builder(this)
    .setContentTitle("Flashlight Controller")
    .setContentText("Click here to turn on/off the lights").setSmallIcon(R.drawable.icon)
    .setContentIntent(pIntent)

    .addAction(R.drawable.ic_launcher, "Call", pIntent)
    .addAction(R.drawable.ic_launcher, "More", pIntent)
    .addAction(R.drawable.ic_launcher, "And more", pIntent).build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// hide the notification after its selected
noti.flags |= Notification.FLAG_ONGOING_EVENT;

notificationManager.notify(0, noti);

}

}
布局xml

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >

<Button
    android:id="@+id/button1"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:onClick="createNotification"
    android:text="Create Notification" >
</Button>

<Button
android:id="@+id/cancel"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:onClick="clearNotification"
android:text="Cancel notification" />

</LinearLayout>

只需使用具有相同通知ID的NotificationManager cancel方法: