Android Notification通知栏的必备姿势

android开发,可能经常使用到通知管理者,在手机顶部显示通知。封装一些常用的方法,可以减少代码冗余。通常情况下,显示下载进度,播放器通知栏操作,显示APP状态信息,发送友情提示等,都需要用到Notification。

一,直接贴代码,直观了解通知栏。

/**
 * Created by duqian on 16/01/23.
 * Android通知栏封装
 */
public class NotificationUtils {

    private static final int SmallIcon = R.drawable.ic_launcher;
    public static final int NotificationNumber = 1;
    private static NotificationManager mManager;
    private static NotificationCompat.Builder mBuilder;
    private static final Random RANDOM = new Random();
    /**
     * 获取Builder
     */
    public static NotificationCompat.Builder getBuilder(Context context) {
        mBuilder = new NotificationCompat.Builder(context);
        mBuilder.setNumber(NotificationNumber)
                .setWhen(System.currentTimeMillis())
                .setPriority(Notification.PRIORITY_DEFAULT)
                .setAutoCancel(true);
              //.setDefaults(Notification.DEFAULT_VIBRATE);
        return mBuilder;
    }

    /**
     * 获取NotificationManager
     */
    public static NotificationManager getManager(Context context) {

        if (mManager == null) {
            synchronized (NotificationUtils.class) {
                if (mManager == null) {
                    mManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
                }
            }
        }
        return mManager;
    }


    /**
     * 显示普通的通知
     */
    public static void showOrdinaryNotification(Context context, String title, String text, String ticker,
                                                int icon, int channel) {
        mBuilder = getBuilder(context);
        mManager = getManager(context);
        mBuilder.setContentTitle(title)
                .setContentText(text)
                .setContentIntent(getDefalutIntent(context, Notification.FLAG_AUTO_CANCEL))
                .setNumber(NotificationNumber)//显示数量
                .setTicker(ticker)//通知首次出现在通知栏,带上升动画效果的,可设置文字,图标
                .setWhen(System.currentTimeMillis())//通知产生的时间
                .setPriority(Notification.PRIORITY_DEFAULT)//设置该通知优先级
                .setAutoCancel(true)//设置让通知将自动取消
                .setOngoing(false)//ture,设置他为一个正在进行的通知。如一个文件下载,网络连接。
                .setDefaults(Notification.DEFAULT_SOUND)//向通知添加声音、闪灯和振动效果。最简单、最一致的方式是使用当前的用户默认设置,使用defaults属性,可以组合:
                        //Notification.DEFAULT_ALL  Notification.DEFAULT_SOUND 添加声音 //DEFAULT_VIBRATE requires VIBRATE permission
                .setSmallIcon(SmallIcon)
        ;
        Notification mNotification = mBuilder.build();
        mNotification.icon = icon;
        mManager.notify(dealWithId(channel), mNotification);
    }
    //获取默认的延期意图
    public static PendingIntent getDefalutIntent(Context context, int flags) {
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, new Intent(), flags);
        return pendingIntent;
    }
    //通知channel ID,唯一标示一个通知
    public static int dealWithId(int channel) {
        return channel >= 1 && channel <= 100 ? channel : RANDOM.nextInt(Integer.MAX_VALUE - 100) + 101;
    }
    //获取系统SDK版本
    public static int getSystemVersion() {
        int version = android.os.Build.VERSION.SDK_INT;
        return version;
    }

    /**
     * 清除所有的通知
     * @param context
     */
    public static void clearAllNotifification(Context context) {
        mManager = getManager(context);
        mManager.cancelAll();
    }

    /**
     * 清除通知
     */
    public static void clearNotifificationById(Context context, int channel){
        mManager = getManager(context);
        mManager.cancel(dealWithId(channel));
    }
    private static int iconId = 0;

    public void setIconId(int iconId){
        this.iconId=iconId;
    }
    /**
     * 默认图标
     */
    private static int getPushIconId(Context context) {
        if(iconId==0)
        {
            iconId = context.getApplicationInfo().icon;
        }
        if (iconId < 0) {
            iconId = android.R.drawable.sym_def_app_icon;
        }
        return iconId;
    }
    //去通知文本的前15位字符
    private  static String getSubStringTitle(String desc) {
        if (desc != null && !"".equals(desc) && desc.length() > 15) {
            return desc.substring(0, 15);
        } else {
            return desc;
        }
    }
 }
/**
     * 显示进度的通知栏
     */
    public static void showProgressNotification(Context context, String title, String text, String ticker,
                                                Intent resultIntent, boolean indeterminate, int progress,
                                                int icon, int channel) {
        mBuilder = getBuilder(context);
        mManager = getManager(context);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, RequestCode, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentTitle(ticker)//ticker,title
                .setContentText(text)
                .setTicker(ticker)
                .setSmallIcon(SmallIcon)
                .setContentIntent(pendingIntent);
        if (indeterminate) {
            //不确定进度的 设置为true就是不确定的那种进度条效果
            mBuilder.setProgress(0, 0, true).setOngoing(false).setAutoCancel(true);
        } else {
            //确定进度的
            mBuilder.setProgress(100, progress, false).setOngoing(true);
        }

        Notification progressNotification = mBuilder.build();
        progressNotification.icon = icon;
        mManager.notify(dealWithId(channel), progressNotification);
    }
 /**
     * 带意图的通知栏:Intent 中可以包含很多参数、功能
     * 应用场景:页面启动、跳转、安装apk
     */
    public static void showIntentNotification(Context context, String title, String text, String ticker,
                                              Intent resultIntent, int icon, int channel,int defaults) {
        mBuilder = getBuilder(context);
        mManager = getManager(context);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, RequestCode, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentTitle(title)
                .setContentText(text)
                .setTicker(ticker)
                .setSmallIcon(SmallIcon)
                .setContentIntent(pendingIntent);
        if (defaults>0){
            mBuilder.setDefaults(Notification.DEFAULT_SOUND);
        }
        Notification mNotification = mBuilder.build();
        mNotification.icon = icon;
        mManager.notify(dealWithId(channel), mNotification);

    }

二,如何调用呢?

    //提示存储空间不足,跳转到某个页面
    private void notifyNotEnoughSpace(Context context) {
        String title = context.getString(R.string.error_sdcard_storage_full);
        String text = context.getString(R.string.buy_oair_device);
        String ticker = title;

        Intent resultIntent = new Intent(context,SimpleWebActivity.class);
        resultIntent.putExtra(MyConstant.intent_plugin_url,OairApi.oair_buy_product);
        resultIntent.putExtra(MyConstant.intent_plugin_name, context.getString(R.string.webview_oair_title));
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        NotificationUtils.showIntentNotification(context, title,text, ticker, resultIntent, R.drawable.ic_launcher, channel_download_ocloud,Notification.DEFAULT_ALL);//Notification.DEFAULT_SOUND
        //NotificationUtils.showOrdinaryNotification(context, title,text, ticker,R.drawable.logo_statusbar,channel_download_ocloud);
        //ToastUtils.showCenterToast(context,title+","+text);
    }

三,自定义通知View

以上通知栏,图标,位置随手机系统规格来。我们也可以自定义通知栏的布局。通过引入xml中定义好的布局,然后更新通知栏的UI。

//显示应用有更新的通知,显示下载进度,下载完成点击后可以安装或其他操作
    private void showNotifycation(Context context) {
        String title = context.getString(R.string.notify_download_apk);
        String text = context.getString(R.string.notify_click_apk_download);
        String ticker = title;
        Notification n = new Notification(R.drawable.ic_launcher,ticker, System.currentTimeMillis());
        Intent clickIntent = new Intent();
        clickIntent.setAction(BroadcastUtils.ACTION_NOTIFICATION);
        clickIntent.putExtra(BroadcastUtils.CATEGORY,BroadcastUtils.category_apk_download_install);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        n.setLatestEventInfo(context, title, text, pendingIntent);
        n.flags |= Notification.FLAG_AUTO_CANCEL; //点击一次后自动消除
        final int hours = new Date().getHours();
        LogUtils.debug(TAG,"hours="+hours);
        if (hours>=8&&hours<=24) {
            n.defaults = Notification.DEFAULT_ALL;
        }
        NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        nm.notify(channel_download_apk, n);
    }

通过代码可以看出,Notification的使用姿势还是比较简单的,而且通用,暂时没有兼容性问题。我自己用的挺好,是否优雅,自己验证哈。
未完待续,Dusan,Q291902259,欢迎交流。

你可能感兴趣的:(Android,Base,Android,Advanced)