notification-应用实例

这几天接触到了notification,现在就把它的常用方法总结下。

直接看如下代码就行了

ComponentName componetName = new ComponentName("com.android.gallery3d",
                "com.android.camera.CameraLauncher");
        intent = new Intent();
        intent.setComponent(componetName);
        //第一个参数不能随便写,因该有地方用到了它
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notify);
        Drawable drawable =this.getResources().getDrawable(R.drawable.ic_launcher);
        Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
        pendingIntent = PendingIntent.getActivity(this, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder = new Notification.Builder(this)
                .setTicker("haha")//当通知来的时候,滚动显示在状态栏上的文本
                //点击通知,是否把通知从通知栏移除
                .setAutoCancel(true)
                //通知栏自定义布局,覆盖setconttext、title方法
                .setContent(remoteViews)
                //没有自定义布局的情况下,显示在通知栏上的标题跟描述内容
                .setContentText("contentext").setContentTitle("contextile")
                //正在进行的事件,不明白什么作用
                .setOngoing(true)
                //是否在通知栏默认布局上显示通知时间
                .setShowWhen(false)
                //显示在通知栏跟状态栏的小图标。这个必须有,否则通知不会起效果,虽然并不会报错
                .setSmallIcon(R.drawable.abc_ab_bottom_solid_dark_holo)
                //大图标,显示在通知栏上,这时候,小图标会显示在大图表右下角
                .setLargeIcon(bitmap)
                //通知栏点击事件启动
                .setContentIntent(pendingIntent);
                
        notification = builder.build();
        notificationManager = (NotificationManager) this
                .getSystemService(Context.NOTIFICATION_SERVICE);
        bt1 = (Button) findViewById(R.id.bt1);
        bt2 = (Button) findViewById(R.id.bt2);
        bt3 = (Button) findViewById(R.id.bt3);
        bt1.setOnClickListener(new OnClickListener() {

            @SuppressLint("NewApi")
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                notificationManager.notify(100, notification);
                notificationManager.notify(101, notification);

            }
        });
        bt2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
notificationManager.cancelAll();
            }
        });

结果如下

通知栏的使用其实也非常的简单,我们只要知道它上面的几条常用属性就行了。

原文地址:https://www.cnblogs.com/zhangshuli-1989/p/zhangshuli_noti_15713132.html