Android中Notification详细讲解(一)

来源:互联网 发布:网络教育本科怎么报名 编辑:程序博客网 时间:2024/06/04 21:14

这里写图片描述
这里写图片描述
这里写图片描述
官方自述代码块
简单通知代码块
带按钮事件事件代码块
应用一个布局到一个通知代码块
自定义一个通知代码块
自定义一个通知重复出现代码块
添加内嵌回复操作代码块
添加内嵌回复操作代码块只能使用Android 7.0以上手机才能参看,不然都会出现RemoteInput找不到文件的异常
设置一个进度条代码块

主页面布局代码activity_main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.jasen.notificationutil.MainActivity">    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:textSize="25dp"        android:textStyle="bold"        android:textColor="#444"        android:text="Notification总结"/>    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="官方自述"        android:onClick="btnSimple"        />    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="简单通知带点击点击"        android:onClick="btnSimpleClick"        />    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="带按钮事件通知"        android:onClick="btnNotificationClick"        />    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="应用一个布局到一个通知"        android:onClick="expandedLayout"        />    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="自定义一个通知"        android:onClick="btnDefineNotification"        />    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="自定义一个通知,重复出现,不取消"        android:onClick="btnDefineNotification2"        />    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="添加内嵌回复操作"        android:onClick="AddingInlineReplyActions"        />    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal"        >        <Button            android:id="@+id/bt1"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_weight="1"            android:onClick="btnProgressStart"            android:text="进度开始"            />        <Button            android:id="@+id/bt2"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_weight="1"            android:onClick="btnCancelAll"            android:text="清除通知"            />    </LinearLayout></LinearLayout>

官方自述代码块

public void btnSimple(View view) {        NotificationCompat.Builder mBuilder =                new NotificationCompat.Builder(this)                        .setSmallIcon(R.mipmap.ic_launcher)                        .setContentTitle("TaskStackBuilder")                        .setContentText("官方标准代码");//        NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle(mBuilder);// Creates an explicit intent for an Activity in your app        Intent resultIntent = new Intent(this, MainActivity.class);// The stack builder object will contain an artificial back stack for the// started Activity.// This ensures that navigating backward from the Activity leads out of// your application to the Home screen.        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);// Adds the back stack for the Intent (but not the Intent itself)        stackBuilder.addParentStack(MainActivity.class);// Adds the Intent that starts the Activity to the top of the stack        stackBuilder.addNextIntent(resultIntent);        PendingIntent resultPendingIntent =                stackBuilder.getPendingIntent(                        0,                        PendingIntent.FLAG_UPDATE_CURRENT                );        mBuilder.setContentIntent(resultPendingIntent);        NotificationManager mNotificationManager =                (NotificationManager) getSystemService(this.NOTIFICATION_SERVICE);// mId allows you to update the notification later on.        mNotificationManager.notify(1, mBuilder.build());    }

简单通知代码块

 public void btnSimpleClick(View view) {        mBuilder = new NotificationCompat.Builder(this);        mBuilder.setSmallIcon(R.mipmap.ic_launcher).                setContentTitle("简单通知").                setContentText("这是一个简单通知,点击通知到主界面").                setTicker("测试通知来了")                .setSound(Uri.parse("android.resource://"                + getPackageName() + "/" +R.raw.rcalifrag));        Intent intent = new Intent(this, MainActivity.class);        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent                .FLAG_UPDATE_CURRENT);        mBuilder.setContentIntent(pendingIntent);        mBuild = mBuilder.build();        //让声音、振动无限循环,直到用户响应        mBuilder.setSound(Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI,"6"));        mBuild.flags = Notification.FLAG_INSISTENT;        //通知被点击后,自动消失        mBuild.flags |= Notification.FLAG_AUTO_CANCEL;        mManagerCompat = NotificationManagerCompat.from(this);        mManagerCompat.notify(2,mBuild);    }

带按钮事件事件代码块

 public void btnNotificationClick(View view) {        mBuilder = new NotificationCompat.Builder(this);        mBuilder.setContentText("你点击的是一个带按钮事件的通知,当你接收其他通知时,此通知会收").                setContentTitle("带按钮的通知,就问你6不6?").                setSmallIcon(R.mipmap.ic_launcher).                setTicker("老板,你的通知到了")        ;        Intent intent = new Intent(this, MainActivity.class);        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,                PendingIntent.FLAG_UPDATE_CURRENT);        mBuilder.setContentIntent(pendingIntent);        mBuilder.addAction(android.R.drawable.ic_media_play, "播放", pendingIntent);        mBuilder.addAction(android.R.drawable.ic_media_play, "播放", pendingIntent);        mBuilder.addAction(android.R.drawable.ic_media_play, "播放", pendingIntent);        mBuild = mBuilder.build();        mBuild.defaults |= Notification.DEFAULT_SOUND;        mBuild.defaults |= Notification.DEFAULT_VIBRATE;        mBuild.defaults |= Notification.DEFAULT_LIGHTS;        //让声音、振动无限循环,直到用户响应        mBuild.flags |= Notification.FLAG_INSISTENT;        //通知被点击后,自动消失        mBuild.flags |= Notification.FLAG_AUTO_CANCEL;        //点击'Clear'时,不清楚该通知(QQ的通知无法清除,就是用的这个//        mBuild.flags |= Notification.FLAG_NO_CLEAR;        mManagerCompat = NotificationManagerCompat.from(this);        mManagerCompat.notify(3, mBuild);    }

应用一个布局到一个通知代码块

public void expandedLayout(View view) {        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)                .setSmallIcon(android.R.drawable.ic_dialog_email)                .setContentTitle("Builder.setContentTitle的内容")                .setContentText("Builder.setContentText的内容");        NotificationCompat.InboxStyle inboxStyle =                new NotificationCompat.InboxStyle();        String[] events = new String[6];// Sets a title for the Inbox in expanded layout        inboxStyle.setBigContentTitle("这是inboxStyle的Title");        inboxStyle.addLine("这个是第一行");        inboxStyle.addLine("这个是第二行");        inboxStyle.addLine("这个是第三行");        inboxStyle.addLine("这个是第四行");        inboxStyle.setSummaryText("这是inboxStyle.setSummaryText显示的内容");// Moves events into the expanded layout        for (int i=0; i < events.length; i++) {            inboxStyle.addLine(events[i]);        }// Moves the expanded layout object into the notification object.        mBuilder.setStyle(inboxStyle);        Notification build = mBuilder.build();        NotificationManagerCompat from = NotificationManagerCompat.from(this);        from.notify(4,build);    }

自定义一个通知代码块

 public void btnDefineNotification(View view) {        Intent intent = new Intent(this, MainActivity.class);        // display the notification        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);        NotificationManager mNotificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);// Android 2.x does not support remote view + custom notification concept using// support library        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {            mBuilder.setSmallIcon(R.mipmap.ic_launcher);            mBuilder.setContentTitle("Builder.setContentTitle的内容")                    .setStyle(                            new NotificationCompat.BigTextStyle()                                    .bigText("mBuilder.BigText的内容"))                    .setAutoCancel(true).setDefaults(Notification.DEFAULT_SOUND)                    .setLights(Color.WHITE, 500, 500)                    .setContentText("mBuilder.setContentText的内容");        } else {            RemoteViews customNotificationView = new RemoteViews(getPackageName(),                    R.layout.custom_notification);            customNotificationView.setImageViewResource(R.id.notificationIcon,  R.mipmap.ic_launcher);            customNotificationView.setTextViewText(R.id.notificationTitle, "RemoteViews.setTextViewText的内容");            customNotificationView.setTextViewText(R.id.notificationContent, "RemoteViews.setTextViewTextNotificationContent的内容");            mBuilder.setContent(customNotificationView);            mBuilder.setSmallIcon(R.mipmap.ic_launcher);            mBuilder.setAutoCancel(true);            mBuilder.setDefaults(Notification.DEFAULT_SOUND);            mBuilder.setLights(Color.WHITE, 500, 500);        }// build notification        mBuilder.setContentIntent(pendingIntent);        mNotificationManager.notify(1000, mBuilder.build());    }

自定义一个通知重复出现代码块

 public void btnDefineNotification2(View view) {        Intent intent = new Intent(this, MainActivity.class);        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);// display the notification        NotificationManager mNotificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)                .setSmallIcon(android.R.drawable.ic_delete)                .setContentTitle("BuilderTitle内容")                .setStyle(new NotificationCompat.BigTextStyle()                        .bigText("bigText内容"))                .setAutoCancel(true)                .setDefaults(Notification.DEFAULT_SOUND)                .setContentText("setContentText")                .setTicker("Boss,你的老婆来了");        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification);        contentView.setImageViewResource(R.id.notificationIcon, android.R.drawable.stat_sys_vp_phone_call);        contentView.setTextViewText(R.id.notificationTitle, "RemoteViews.setTextViewText的内容");        contentView.setTextViewText(R.id.notificationContent, "感觉木有爱了");        mBuilder.setContent(contentView);        mBuilder.setAutoCancel(true);// build notification        mBuilder.setContentIntent(pendingIntent);        mNotificationManager.notify((int) SystemClock.currentThreadTimeMillis(), mBuilder.build());    }

添加内嵌回复操作代码块

 @TargetApi(Build.VERSION_CODES.KITKAT_WATCH)    public void AddingInlineReplyActions(View view) {        Intent intent = new Intent(this,MainActivity.class);        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,                PendingIntent.FLAG_UPDATE_CURRENT);        String replyLabel = getResources().getString(R.string.reply_label);        RemoteInput remoteInput = new RemoteInput.Builder(KEY_TEXT_REPLY)                .setLabel(replyLabel)                .build();        Notification.Action action =                new Notification.Action.Builder(R.mipmap.ic_launcher,                        "回复操作", pendingIntent)                        .addRemoteInput(remoteInput)                        .build();        // Build the notification and add the action.        Notification newMessageNotification =                new Notification.Builder(this)                        .setSmallIcon(R.mipmap.ic_launcher)                        .setContentTitle("Notification.setContentTitle")                        .setContentText("Notification.setContentText")                        .setSound(Uri.parse("android.resource://"                                + getPackageName() + "/" +R.raw.rcalifrag))                        .addAction(action).build();// Issue the notification.        NotificationManagerCompat notificationManager =                NotificationManagerCompat.from(this);        notificationManager.notify(6, newMessageNotification);    }

设置一个进度条代码块

  int notification_id=19172439;    NotificationManager nm;    Handler handler=new Handler();    Notification notification;    int count=0;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);        notification=new Notification(R.mipmap.ic_launcher,"图标边的文字",System.currentTimeMillis());        notification.contentView = new RemoteViews(getPackageName(),R.layout.progress_notification);        //使用notification.xml文件作VIEW        notification.contentView.setProgressBar(R.id.pb, 100,0, false);        //设置进度条,最大值 为100,当前值为0,最后一个参数为true时显示条纹        //(就是在Android Market下载软件,点击下载但还没获取到目标大小时的状态)        Intent notificationIntent = new Intent(this,MainActivity.class);        PendingIntent contentIntent = PendingIntent.getActivity(this,0,notificationIntent,0);        notification.contentIntent = contentIntent;    }public void btnProgressStart(View view) {        // TODO Auto-generated method stub        showNotification();//显示notification        handler.post(run);    }    public void btnCancelAll(View view) {        nm.cancel(notification_id);    }

作者参考博客地址:
Android 状态栏通知Notification、NotificationManager详解
通知栏Notification自定义视图方法(显示进度条)

0 0
原创粉丝点击