一个封装好的nofication类

来源:互联网 发布:浙江淘宝村在哪里 编辑:程序博客网 时间:2024/06/06 11:02

最近在做项目,需要利用socket来实时通信,有个需求是客户端的socket收到服务器发送的消息,需要显示一个消息提醒,这个时候就用到了notification这个类。

然后网上找了资料,封装了一个工具类

public class ChatNotification {    private Context context;    private NotificationManager notificationManager;    private Notification callingNotification;    private static final int CALLING_NOTIFY_ID = 111;        public ChatNotification(Context context) {        this.context = context;         notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);    }    private void buildCallingNotification() {        if (callingNotification == null) {            Intent localIntent = new Intent();            localIntent.setClass(context, AlarmListActivity.class);//点击进入的页面            localIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);            String tickerText ="您有新的待接警电话,请点击查看"; //显示的文字            int iconId = R.drawable.app_logo; //显示的图标            PendingIntent pendingIntent = PendingIntent.getActivity(context, CALLING_NOTIFY_ID, localIntent, PendingIntent                    .FLAG_UPDATE_CURRENT);            callingNotification = makeNotification(pendingIntent, "报警提醒", tickerText, tickerText,                    iconId, true, false);        }    }    private Notification makeNotification(PendingIntent pendingIntent, String title, String content, String tickerText,                                          int iconId, boolean ring, boolean vibrate) {        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);        builder.setContentTitle(title)                .setContentText(content)                .setAutoCancel(true)                .setContentIntent(pendingIntent)                .setTicker(tickerText)                .setSmallIcon(iconId);        int defaults = Notification.DEFAULT_LIGHTS;        if (vibrate) {            defaults |= Notification.DEFAULT_VIBRATE;//设置震动        }        if (ring) {            defaults |= Notification.DEFAULT_SOUND; //设置铃声        }        builder.setDefaults(defaults);        return builder.build();    }    /**     * true表示发送通知     * false表示取消通知     * @param active     */    public void activeCallingNotification(boolean active) {        if (notificationManager != null) {            if (active) {                buildCallingNotification();                notificationManager.notify(CALLING_NOTIFY_ID, callingNotification);            } else {                notificationManager.cancel(CALLING_NOTIFY_ID);            }        }    }}



使用方法也很简单,如下

ChatNotification notification=new ChatNotification(this);notification.activeCallingNotification(true);//发送通知notification.activeCallingNotification(false);//取消通知


当然,如果想自定义这个通知的文本和显示图标等,可以在buildingCallingNotification这个方法里修改,注释都有写了,如果需要更灵活,可以根据需要再次修改下该方法。


0 0
原创粉丝点击