西狂杨过 2015-03-03
本实例示范了如何通过NotificationManager来发送和取消notification,界面很简单,只是包括了2个普通按钮,分别用于发送和取消Notification,代码如下:
package com.example.notifition; import android.annotation.SuppressLint; 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 MainActivity extends Activity { private static final int NOTIFICATION_ID = 123; private NotificationManager nm; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Button btnSend = (Button) findViewById(R.id.btn_send); Button btnCancel = (Button) findViewById(R.id.btn_cancel); btnSend.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { send(); } }); btnCancel.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { remove(); } }); } //发送 @SuppressLint("NewApi") public void send (){ //创建一个启动其它activity的Intent Intent intent = new Intent(MainActivity.this, OtherActivity.class); PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, intent, 0); Notification notification = new Notification.Builder(MainActivity.this) .setAutoCancel(true)//设置打开该通知,该通知自动消失 .setTicker("有新消息")//设置显示状态栏的通知提示信息 .setSmallIcon(R.drawable.ic_launcher)//设置通知的图标 .setContentTitle("有一条新通知")//设置通知的标题 .setContentText("恭喜您,您中了现金500w")//设置通知的内容 .setDefaults(Notification.DEFAULT_SOUND |Notification.DEFAULT_LIGHTS)//设置系统默认的声音 .setWhen(System.currentTimeMillis())//设置通知的时间 .setContentIntent(pi).build()//设置intent ; nm.notify(NOTIFICATION_ID,notification);//发送通知 } //取消通知 public void remove(){ nm.cancel(NOTIFICATION_ID);//取消通知栏,调用该方法后,通知栏就会消失 //还可以使用setSounds来设置声音 } }