Notification 通知栏

来源:互联网 发布:三茅招聘软件 编辑:程序博客网 时间:2024/05/22 03:22
通知栏内容:
  • 图标
  • 标题
  • 内容
  • 时间
  • 点击后响应

实现通知栏通知
  • 获取NotificationManager
  • 显示通知栏:notify(id,notification);
  • 取消通知栏:cancle(id);
  • 构造Notification并设置显示内容
  • 通知栏通知可以设置声音提示,指示灯,以及震动效果

需要注意的是:
要实现通知栏推送的指示灯和震动效果 需要 Permission权限
需要用NotificationManager来进行实现

example:
----------------------------------------------------------------------------------------------------
public class MainActivity extends Activity implements OnClickListener{
 NotificationManager manager;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
   // NotificationManager是一个系统服务 通过这种方法获取
  manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  findViewById(R.id.bt1).setOnClickListener(this);
  findViewById(R.id.bt2).setOnClickListener(this);
 }

 public void onClick(View v) {
  // TODO Auto-generated method stub
  switch (v.getId()) {
  case R.id.bt1:
   sendNotification();
   break;

  case R.id.bt2:
   manager.cancel(0);
   break;
  }
 }
 
 private void sendNotification() {
  // TODO Auto-generated method stub
  Intent intents =new Intent(this,MainActivity.class);
  // Intent 为 启动该 Activity
  PendingIntent pending = PendingIntent.getActivity(this, 0, intents, 0);
   //设置一个 pending Intent,参数依次为上下文 请求码 intent对象 标记
  android.app.Notification.Builder builder = new Notification.Builder(this);
  builder.setSmallIcon(R.drawable.ic_launcher);//图标
  builder.setTicker("Hello");//状态栏的文字
  builder.setWhen(System.currentTimeMillis());
  builder.setContentTitle("通知");//设置标题
  builder.setContentText("我是一个通知栏");//设置通知内容
  builder.setContentIntent(pending);//点击后执行的intent
  builder.setDefaults(Notification.DEFAULT_SOUND);//设置声音
  builder.setDefaults(Notification.DEFAULT_LIGHTS);//设置指示灯
  builder.setDefaults(Notification.DEFAULT_VIBRATE);//设置震动
  builder.setDefaults(Notification.DEFAULT_ALL);//设置以上三种
  Notification notification = builder.build();
  manager.notify(0, notification);
 }
 

}
0 0
原创粉丝点击