java代码
package mars.com; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class Demo extends Activity { private Notification notification; private NotificationManager notificationManager; private Button button1; private Button button2; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); button1 = (Button) findViewById(R.id.button1); button2 = (Button) findViewById(R.id.button2); String service = NOTIFICATION_SERVICE;// 获取系统服务 notificationManager = (NotificationManager) getSystemService(service); notification = new Notification(); notification.icon = R.drawable.ic_launcher;// 指定图标 notification.tickerText = "测试";// 指定提示信息 notification.when = System.currentTimeMillis();// 指定时间 button1.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(Demo.this, Demo.class); PendingIntent pendingIntent = PendingIntent.getActivity( Demo.this, 0, intent, 0); notification.setLatestEventInfo(Demo.this, "我的标题", "我的内容", pendingIntent); notificationManager.notify(1, notification);// 发出通知 } }); button2.setOnClickListener(new OnClickListener() { public void onClick(View v) { notificationManager.cancel(1);// 取消通知 } }); } }
xml文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="发出通知" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="取消通知" /> </LinearLayout>