安卓消息通知类Notification、NotificationManager

安卓消息通知类,分别是发送消息、更新消息、删除消息的例子:

 

class NotifyEx {
    private Notification notify;
    private Context mContext;
    private NotificationManager Nm;
    private Intent intent;
    private static int NOTIFITY_ID = 0x123;
    private static final String TAG = "NotifyEx";
    private static int count = 1;

    public NotifyEx(Context c){
        mContext = c;
        Nm = (NotificationManager)c.getSystemService(Context.NOTIFICATION_SERVICE);
    }

    /**
     * 发送通知消息
     * @param cls 需要启动的Class
     * @param Ticker 通知标题
     * @param title 消息标题
     * @param context 消息内容
     * @return
     */
    public boolean send(Class<?> cls,String Ticker,String title,String context){
        intent = new Intent(mContext,cls);
        PendingIntent pi = PendingIntent.getActivity(mContext,0,intent,0);
        notify = new Notification.Builder(mContext)
                .setAutoCancel(true)
                .setTicker(Ticker)//通知标题
                .setSmallIcon(R.drawable.notice_tag)//图标
                .setContentTitle(title)//提示标题
                .setContentText(context)//提示内容
                .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS)//系统默认的声音
                // .setSound(Uri.parse("android.resource://com.lanxin.ui"+R.raw.msg)).setWhen(System.currentTimeMillis())自定义声音
                .setContentIntent(pi).build();

        Nm.notify(NOTIFITY_ID,notify);
        Log.i(TAG,String.valueOf(NOTIFITY_ID));
        return true;
    }

    /**
     * 发送第二条消息(消息通知更新)
     * @param cls 需要启动的class
     * @param Ticker 通知标题
     * @param title 消息标题
     * @param context 消息内容
     * @return
     */
    public boolean update(Class<?> cls,String Ticker,String title,String context){
        count++;
        intent = new Intent(mContext,cls);
        PendingIntent pi = PendingIntent.getActivity(mContext,0,intent,0);
        notify = new Notification.Builder(mContext)
                .setAutoCancel(true)
                .setTicker("您有"+count+"条信息未读")//通知标题
                .setSmallIcon(R.drawable.notice_tag)//图标
                .setContentTitle(title)//提示标题
                .setContentText(context)//提示内容
                .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS)//系统默认的声音
                // .setSound(Uri.parse("android.resource://com.lanxin.ui"+R.raw.msg)).setWhen(System.currentTimeMillis())自定义声音
                .setContentIntent(pi).build();

        Nm.notify(NOTIFITY_ID,notify);//只要这个ID是一样的就可以更新

        Log.i(TAG,String.valueOf(NOTIFITY_ID));
        Log.i(TAG, String.valueOf(count));
        return true;
    }

    public boolean del(){
        Nm.cancel(NOTIFITY_ID);
        Log.i(TAG, String.valueOf(NOTIFITY_ID));
        return true;
    }

    /**
     * 返回当前消息条数
     * @return
     */
    public int getCount(){
        return count;
    }

}

Leave a Comment

 
Copyright © 2008-2021 lanxinbase.com Rights Reserved. | 粤ICP备14086738号-3 |