Notification

转载请标明出处: :http://blog.youkuaiyun.com/huaiyiheyuan/article/details/52473984
通知

  通知是您可以在应用的常规 UI 外部向用户显示的消息。当您告知系统发出通知时,它将先以图标的形式显示在通知区域中。用户可以打开抽屉式通知栏查看通知的详细信息。 通知区域和抽屉式通知栏均是由系统控制的区域,用户可以随时查看。

一、创建通知

1、创建简单通知

   Notification对象包括
    小图标,由 setSmallIcon() 设置
    标题,由 setContentTitle() 设置
    详细文本,由 setContentText() 设置
  2、官方示例basicNotificaitons
     改了一点效果如图
     /**
     * 一
     * 创建基本通知
     *
     * @param view
     */
    public void sendBasicNotification(View view) {

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_stat_notification)
                /**
                 * 点击导航条,控制跳转按钮
                 */
                .setContentIntent(resultPendingIntent)
                //点击后消失
                .setAutoCancel(true)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.i_btn_ins))

                .setContentTitle("BasicNotifications Sample")
                .setContentText("Time to learn about notifications!")
                .setSubText("Tap to view documentation about notifications.");


//        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
//        stackBuilder.addParentStack(OtherActivity.class);
//        stackBuilder.addNextIntent(resultIntent);

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }

 效果如图,感觉smallicon有问题,先往下看

这里写图片描述

备注:需要注意的是 在小米 ,乐视上,setLargeIcon这个方法不起作用,为了适配这些手机,我目前的办法是使用自定义布局 setCustomContentView来实现

2、更新通知 :

 要将通知设置为能够更新,请通过调用 NotificationManager.notify() 发出带有通知 ID 的通知。 要在发出之后更新此通知,请更新或创建 NotificationCompat.Builder 对象,从该对象构建 Notification 对象,并发出与之前所用 ID 相同的 Notification。如果之前的通知仍然可见,则系统会根据 Notification 对象的内容更新该通知。相反,如果之前的通知已被清除,系统则会创建一个新通知。

以下代码段演示了经过更新以反映所发生事件数量的通知。 它将通知堆叠并显示摘要:
动图

    /**
     * 更新通知
     *
     * @param view
     */
    public void updateNotification(View view) {
        final NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // Sets an ID for the notification, so it can be updated
        final NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(this)
                .setContentTitle("New Message")
                .setContentText("You`ve received new Messages.")
                .setSmallIcon(R.mipmap.ic_stat_notification);

        Executors.newCachedThreadPool().submit(new Runnable() {
            @Override
            public void run() {
                int numMessages = 0;
                while (numMessages < 20) {

                    // Start of a loop that processes data and then notifies the user
                    mNotifyBuilder.setContentText("hehe")
                            .setNumber(++numMessages);
                    // Because the ID remains unchanged, the existing notification is
                    // updated.
                    mNotificationManager.notify(nitifyT, mNotifyBuilder.build());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

3、TaskStackBuilder 的使用:待跟进
常规 Activity
特殊 Activity

二、在通知栏显示进度

    ![这里写图片描述](https://img-blog.youkuaiyun.com/20160922145528961)

1、 显示持续时间固定的进度指示器

    /**
     * 显示进度条
     *
     * @param view
     */
    public void showProgress(View view) {
        mBuilder.setContentTitle("Picture Download")
                .setContentText("Download in progress")
                .setSmallIcon(R.mipmap.ic_circle);
        Executors.newCachedThreadPool().submit(new Runnable() {
            @Override
            public void run() {
                int incr;
                for (incr = 0; incr <= 100; incr += 20) {
                    mBuilder.setProgress(100, incr, false);
                    mNotificationManager.notify(notifyF, mBuilder.build());
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        Log.d(Tag, "sleep failure");
                    }
                }
                mBuilder.setContentText("Download compete")
                        //Removes the progress bar
                        .setProgress(0, 0, false);
                mNotificationManager.notify(notifyF, mBuilder.build());
            }
        });
    }  

2、显示持续 Activity 指示器

这里写图片描述

// Sets the progress indicator to a max value, the current completion
// percentage, and "determinate" state
mBuilder.setProgress(100, incr, false);
// Issues the notification
mNotifyManager.notify(0, mBuilder.build());
将找到的这几行替换为以下几行:

 // Sets an activity indicator for an operation of indeterminate length
mBuilder.setProgress(0, 0, true);
// Issues the notification
mNotifyManager.notify(0, mBuilder.build())

3、自定义布局

在下面RemoteViews  操作
private void createNotification() {
        // BEGIN_INCLUDE(notificationCompat)
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        // END_INCLUDE(notificationCompat)

        // BEGIN_INCLUDE(intent)
        //Create Intent to launch this Activity again if the notification is clicked.
        Intent i = new Intent(this, MainActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(this, 0, i,
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(intent);
        // END_INCLUDE(intent)

        // BEGIN_INCLUDE(ticker)
        // Sets the ticker text
        builder.setTicker(getResources().getString(R.string.custom_notification));

        // Sets the small icon for the ticker
        builder.setSmallIcon(R.drawable.ic_stat_custom);
        // END_INCLUDE(ticker)

        // BEGIN_INCLUDE(buildNotification)
        // Cancel the notification when clicked
        builder.setAutoCancel(true);

        // Build the notification
        Notification notification = builder.build();
        // END_INCLUDE(buildNotification)

        // BEGIN_INCLUDE(customLayout)
        // Inflate the notification layout as RemoteViews
        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification);

        // Set text on a TextView in the RemoteViews programmatically.
        final String time = DateFormat.getTimeInstance().format(new Date()).toString();
        final String text = getResources().getString(R.string.collapsed, time);
        contentView.setTextViewText(R.id.textView, text);

        /* Workaround: Need to set the content view here directly on the notification.
         * NotificationCompatBuilder contains a bug that prevents this from working on platform
         * versions HoneyComb.
         * See https://code.google.com/p/android/issues/detail?id=30495
         */
        notification.contentView = contentView;

        // Add a big content view to the notification if supported.
        // Support for expanded notifications was added in API level 16.
        // (The normal contentView is shown when the notification is collapsed, when expanded the
        // big content view set here is displayed.)
        if (Build.VERSION.SDK_INT >= 16) {
            // Inflate and set the layout for the expanded notification view
            RemoteViews expandedView =
                    new RemoteViews(getPackageName(), R.layout.notification_expanded);
            notification.bigContentView = expandedView;
        }
        // END_INCLUDE(customLayout)

        // START_INCLUDE(notify)
        // Use the NotificationManager to show the notification
        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        nm.notify(0, notification);
        // END_INCLUDE(notify)
    }

Reference : https://developer.android.com/guide/topics/ui/notifiers/notifications.html#CustomNotification

https://developer.android.com/samples/LNotifications/index.html

下面是代码集成了上面的例子

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值