Android:通知栏的使用

很久没有使用Android的通知功能了,今天把两年前的代码搬出来一看,发现很多方法都废弃了,代码中各种删除线看的十分不爽。于是乎,打开Google,查看官方文档,学习最新的发送通知栏消息的方法。

本文中的代码均参照谷歌官方文档编写:

http://developer.android.com/guide/topics/ui/notifiers/notifications.html

1.首先,获取系统的通知服务:

NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
2.发送一个最简单的通知

    public void simpleNotice(View view) {
        //此Builder为android.support.v4.app.NotificationCompat.Builder中的,下同。
        Builder mBuilder = new Builder(this);
        //系统收到通知时,通知栏上面显示的文字。
        mBuilder.setTicker("天津,晴,2~15度,微风");
        //显示在通知栏上的小图标
        mBuilder.setSmallIcon(R.drawable.consult_answer);
        //通知标题
        mBuilder.setContentTitle("天气预报");
        //通知内容
        mBuilder.setContentText("天津,晴,2~15度,微风");

        //设置大图标,即通知条上左侧的图片(如果只设置了小图标,则此处会显示小图标)
        mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.share_sina));
        //显示在小图标左侧的数字
        mBuilder.setNumber(6);

        //设置为不可清除模式
        mBuilder.setOngoing(true);

        //显示通知,id必须不重复,否则新的通知会覆盖旧的通知(利用这一特性,可以对通知进行更新)
        nm.notify(1, mBuilder.build());
    }
3.删除一个通知。参数即为通知的id
nm.cancel(1);
4.发送一个通知,点击通知后跳转到一个Activity,从这个Activity返回后,进入程序内的某一个页面(一般为主页)

//点击通知进入一个Activity,点击返回时进入指定页面。
    public void resultActivityBackApp(View view) {
        Builder mBuilder = new Builder(this);
        mBuilder.setTicker("通知标题2");
        mBuilder.setSmallIcon(R.drawable.ic_launcher);
        mBuilder.setContentTitle("通知标题2");
        mBuilder.setContentText("点击通知进入一个Activity,点击返回时进入指定页面。");

        //设置点击一次后消失(如果没有点击事件,则该方法无效。)
        mBuilder.setAutoCancel(true);

        //点击通知之后需要跳转的页面
        Intent resultIntent = new Intent(this, ResultActivityBackApp.class);

        //使用TaskStackBuilder为“通知页面”设置返回关系
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        //为点击通知后打开的页面设定 返回 页面。(在manifest中指定)
        stackBuilder.addParentStack(ResultActivityBackApp.class);
        stackBuilder.addNextIntent(resultIntent);

        PendingIntent pIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pIntent);
        // mId allows you to update the notification later on.
        nm.notify(2, mBuilder.build());
    }
同时,需要在manifest中为点击通知后打开的Activity指定父Activity.

<activity
            android:name=".ResultActivityBackApp"
            android:parentActivityName=".MainActivity">

            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />

        </activity>
(其中,activity的属性parentActivityName为API 16中的属性,meta-data中的代码为兼容API 16以下。因此,对于大多数程序,这两个地方都得写。)

5.和上述4类似,只是在打开的Activity中返回时回到home页

 //点击通知进入一个Activity,点击返回时回到桌面
    public void resultActivityBackHome(View view) {
        Builder mBuilder = new Builder(this);
        mBuilder.setTicker("通知标题3");
        mBuilder.setSmallIcon(R.drawable.ic_launcher);
        mBuilder.setContentTitle("通知标题3");
        mBuilder.setContentText("点击通知进入一个Activity,点击返回时回到桌面");

        //设置点击一次后消失(如果没有点击事件,则该方法无效。)
        mBuilder.setAutoCancel(true);

        Intent notifyIntent = new Intent(this, ResultActivityBackHome.class);
        notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pIntent);

        nm.notify(3, mBuilder.build());
    }
6.带进度条的通知

     public void progressNotice(View view) {
        final Builder mBuilder = new Builder(this);
        mBuilder.setTicker("通知标题4");

        mBuilder.setContentTitle("Picture Download")
                .setContentText("Download in progress")
                .setSmallIcon(R.drawable.ic_launcher);

        // Start a lengthy operation in a background thread
        new Thread(new Runnable() {
            @Override
            public void run() {
                int progress;
                for (progress = 0; progress <= 100; progress++) {
                    // Sets the progress indicator to a max value, the current completion percentage,
                    // and "determinate" state
                    mBuilder.setProgress(100, progress, false);

                    //不明确进度的进度条
//                    mBuilder.setProgress(0, 0, true);

                    nm.notify(4, mBuilder.build());
                    // 模拟延时
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                // When the loop is finished, updates the notification
                mBuilder.setContentText("Download complete");
                // Removes the progress bar
                mBuilder.setProgress(0, 0, false);
                nm.notify(4, mBuilder.build());
            }
        }
        ).start();
    }
7.扩展布局的通知。按住通知条下滑,可以查看更详细的内容

public void expandLayoutNotice(View view) {
        Builder mBuilder = new Builder(this);
        mBuilder.setTicker("通知标题5");
        mBuilder.setSmallIcon(R.drawable.ic_launcher);
        mBuilder.setContentTitle("通知标题5");
        mBuilder.setContentText("按住通知下拉可显示扩展布局");

        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
        String[] events = new String[]{"Beijing", "Tianjin", "Shanghai", "Guangzhou"};
        // 设置扩展布局的标题
        inboxStyle.setBigContentTitle("Event tracker details:");

        for (String s : events) {
            inboxStyle.addLine(s);
        }
        mBuilder.setStyle(inboxStyle);

        nm.notify(5, mBuilder.build());
    }

8.自定义布局的通知栏。(根据谷歌的官方文档不推荐这么做,因为使用这种方式时,对不同屏幕进行适配需要考虑的因素太多。而且,通知栏应该展示的就是最简明扼要的信息,对于大多数程序默认的布局已经足够了。)

//自定义布局的通知
    public void customLayoutNotice(View view) {
        Builder mBuilder = new Builder(this);
        mBuilder.setTicker("通知标题6");
        mBuilder.setTicker("通知标题6");
        mBuilder.setSmallIcon(R.drawable.ic_launcher);

        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.custom_layout_notice);
        mBuilder.setContent(remoteViews);
        //为RemoteViews上的按钮设置文字
        remoteViews.setCharSequence(R.id.custom_layout_button1, "setText", "Button1");
        remoteViews.setCharSequence(R.id.custom_layout_button2, "setText", "Button2");

        //为RemoteViews上的按钮设置点击事件
        Intent intent1 = new Intent(this, CustomLayoutResultActivity.class);
        intent1.putExtra("content", "From button1 click!");
        PendingIntent pIntentButton1 = PendingIntent.getActivity(this, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.custom_layout_button1, pIntentButton1);

        Intent intent2 = new Intent(this, CustomLayoutResultActivity.class);
        intent2.putExtra("content", "From button2 click!");
        PendingIntent pIntentButton2 = PendingIntent.getActivity(this, 1, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.custom_layout_button2, pIntentButton2);

        nm.notify(6, mBuilder.build());
    }


你可能感兴趣的:(Android开发,notification)