取消正在进行的通

时间:2014-02-02 13:42:02

标签: android notifications

我有一个主要课程,只需按一下按钮即可完美地启动通知,我刚刚创建了另一个按钮,可以取消正在进行的通知,我应该在下面的代码中添加什么来实现这一目标?

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>

1 个答案:

答案 0 :(得分:0)

只需使用具有相同通知ID的NotificationManager取消方法: http://developer.android.com/reference/android/app/NotificationManager.html#cancel(int)