Android UI之Notification

来源:互联网 发布:算法分析 概述 ppt 编辑:程序博客网 时间:2024/05/16 07:48

Notification和NotificationManager操作相对比较简单,一般获取系统级的服务NotificationManager,然后实例化Notification,设置它的属性,通过NotificationManager发出通知即可。

1 实现通知一般有以下几个步骤

1.获取通知服务对象NotificationManager
2.建立Notification对象,关联intent
3.发出通知

2 代码实现如下:

2.1 获取NotificationManager

/** * 2.获取NotificationManager */NotificationManager mNotificationManager =(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

2.2 建立Notification对象,关联intent

       //取得大图       Bitmap largeIcon = ((BitmapDrawable) getResources().getDrawable(R.drawable.large_icon)).getBitmap();        // 实例化Intent        Intent intent = new Intent(this, SendBroadcastActivity.class);        // 获得PendingIntent        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);       /**         * 2.获得Notification实例         */         // 实例化Notification        Notification notification = new Notification.Builder(this)                .setAutoCancel(true)                .setContentTitle("title")                .setContentText("Test Notification")                .setContentIntent(pi)                .setLargeIcon(largeIcon)                .setSmallIcon(R.mipmap.ic_launcher)                            .setWhen(System.currentTimeMillis())                .build();

2.3 NotificationManager.notify发出通知

       /**         * 3.NotificationManager.notify发出通知         */        // 发出通知        mNotificationManager.notify(1, notification);

3 示例图

这里写图片描述

这里写图片描述

4 其他方法

3.1 其他方法

mNotificationManager.cancel(id);

4 自定义布局

// 设置RemoteViewsRemoteViews remoteViews=new RemoteViews(getPackageName(),R.layout.notify);  // 设置intentIntent intent = new Intent(this, SendBroadcastActivity.class);PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);// 设置自定义内容notification= builder.setContent(remoteViews).setContentIntent(pendingIntent).build(); 
0 0