我们经常可以在Android手机中下拉状态栏时可以看到有许多的推送通知,Android中专门提供了Notification来实现这种效果,如下:
NotificationManager manager = (Notification)getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification();
notification.icon = R.drawable.ic_launcher;//设置通知在状态栏上显示的图标
notification.tickerText = "你有一条新消息";//当通知触发时会显示在状态栏上
//设置下拉状态栏后该通知的布局,可以在自定义Notification布局时使用
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notify);
notification.contentView = remoteViews;
notification.when = System.currentTimeMillis(); //设置通知显示的时间
获得一个PendingIntent对象,用来设置用户点击通知时发生的跳转
Intent newintent = new Intent(this,MainActiviy.class);
PendingIntent pintent = PendingIntent.getActivity(getContext(), 0, newintent, 0);
notification.setLastestEventInfo(getContext(), "这里是通知的标题", "这里是通知的内容", pendingIntent);
manager.notify(1,notification);
manager.notify(1,notification);
manager.notify(2,notification);
manager.notify(3,notification);
manager.cancel(1);
manager.cancelAll();
notification.defaults = notification.DEFAULT_SOUND;
Uri soundUri = Uri.parse("android.resource://"+context.getPackageName()+"/"+R.raw.mysound);
notification.sound = soundUri;
Uri路径前面的那段是通用的,如果要修改成其他的声音的话,只需修改文件名(R.raw.mysound)
notification.defaults = notification.DEFAULT_VIBRATE;
long[] vibrateArgs = new long[]{0,1000,1000,1000,1000,1000};
notification.vibrate = vibrateArgs;
这里传入一个long数组,里面的元素表示:0s后开始震动,且持续震动1s,然后停止1s,接着再震动1s,以此类推
notification.defaults = notification.DEFAULT_LIGHTS;
notification.ledARGB = 0xff0000ff; //【灯光颜色】
notification.ledOnMS = 300; //【亮持续时间】
notification.ledOffMS = 300; //【暗的时间】
NotificationManager manager = (NotificationManager)context.getSystemService(Service.NOTIFICATION_SERVICE);
Notification notification = new Notification();
//设置状态栏的显示
notification.tickerText = "您有一条新消息";
notification.icon = R.drawable.ic_launcher;
//自定义布局
RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.notification_item);
remoteView.setImageViewResource(R.id.icon, R.drawable.ic_launcher);
notification.contentView = remoteView;
//设置状态栏下拉后的显示布局以及点击通知后的跳转
Intent Noticeintent = new Intent(context,NotificationActivity.class);
PendingIntent pintent = PendingIntent.getActivity(context, 0, Noticeintent, 0);
notification.setLatestEventInfo(context, "标题", "内容", pintent);
//设置震动
long[] l = new long[]{0,1000,1000,1000,1000,1000};
notification.vibrate = l;
//设置声音
Uri soundUri = Uri.parse("android.resource://"+context.getPackageName()+"/"+R.raw.mysound);
notification.sound = soundUri;
//发送通知
manager.notify(1, notification);