以前都是直接构造一个通知显示,现在新的api通过builder构建一个通知,有必要学习下。
一、基本用法
基本步骤还是跟以前一样:
1、新建PendingIntent
2、NotificationCompat.Builder调用setContentIntent(PendingIntent)
3、设置图标、文本、标题
4、NotificationManager调用notify()方法
代码详细注释:
package com.example.notification;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
* Created by Administrator on 2015/12/22.
*/
public class BaseUseActivity extends Activity {
private TextView text;
private Button btn_notify;
/**
* A numeric value that identifies the notification that we'll be sending.
* This value needs to be unique within this app, but it doesn't need to be
* unique system-wide.
* 一个代表我们发送的通知的数字值,这个值在app中是唯一的
*/
public static final int NOTIFICATION_ID = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();
}
private void initView() {
text = (TextView) findViewById(R.id.text);
btn_notify = (Button) findViewById(R.id.btn_notify);
text.setText("notification基本用法");
btn_notify.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendNotification();
}
});
}
/**
* Send a sample notification using the NotificationCompat API.
* 用NotificationCompat API发送一个通知
*/
public void sendNotification() {
/** Create an intent that will be fired when the user clicks the notification.
* The intent needs to be packaged into a {@link PendingIntent} so that the
* notification service can fire it on our behalf.
* intent打包进PendingIntent(挂起的intent)中,通知服务能维护我们点击通知的行为
*/
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.baidu.com"));
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
// BEGIN_INCLUDE (build_notification) 构建通知--开始
/**
* Use NotificationCompat.Builder to set up our notification.
* 用NotificationCompat.Builder设置我们的通知
*/
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
/** Set the icon that will appear in the notification bar. This icon also appears
* in the lower right hand corner of the notification itself.
* 设置出现在通知条上的图标,这个图标也出现在右下角。
*
* Important note: although you can use any drawable as the small icon, Android
* design guidelines state that the icon should be simple and monochrome. Full-color
* bitmaps or busy images don't render well on smaller screens and can end up
* confusing the user.
* 重要提示:尽管您可以使用任何drawable作为小图标,Android
* 设计指南声明这个图标应该是简单和单色。在较小的屏幕,全彩
* 位图或繁忙的图像渲染不好
*/
builder.setSmallIcon(R.drawable.ic_stat_notification);
// Set the intent that will fire when the user taps the notification.
//设置挂起的pendingIntent
builder.setContentIntent(pendingIntent);
// Set the notification to auto-cancel. This means that the notification will disappear
// after the user taps it, rather than remaining until it's explicitly dismissed.
//设置通知自动取消。这个意思是用户点击通知后,通知会消失。
builder.setAutoCancel(true);
/**
*Build the notification's appearance.构建通知的外貌
* Set the large icon, which appears on the left of the notification. In this
* sample we'll set the large icon to be the same as our app icon. The app icon is a
* reasonable default if you don't have anything more compelling to use as an icon.
* 设置大图标,这个图标会出现在通知的左边。
*/
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
/**
* Set the text of the notification. This sample sets the three most common only used
* text areas:
* 1. The content title, which appears in large type at the top of the notification
* 2. The content text, which appears in smaller text below the title
* 3. The subtext, which appears under the text on newer devices. Devices running
* versions of Android prior to 4.2 will ignore this field, so don't use it for
* anything vital!
*
* 设置通知的文本。共同的三个文本区域
* 1.内容的标题
* 2.最小字的文本
* 3.subtext,在文本的下面,在4.2之前忽略这个变量,所以如非必要,请不要用这个
*/
builder.setContentTitle("BasicNotifications Sample");
builder.setContentText("Time to learn about notifications!");
builder.setSubText("Tap to view documentation about notifications.");
// END_INCLUDE (build_notification)构建通知--结束
/**
* Send the notification. This will immediately display the notification icon in the
* notification bar.
* 发送通知。这样将会直接在通知栏上显示通知
*/
NotificationManager notificationManager = (NotificationManager) getSystemService(
NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
}
这个例子和下面的例子来自sdk sample,例子中使用的是V4包中的NotificationCompat.Builder。
二、自定义通知内容
主要就是设置notification的contentView
代码:
/*
* Copyright (C) 2013 The Android Open Source Project
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.notification;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.widget.RemoteViews;
import java.text.DateFormat;
import java.util.Date;
public class CustomContentActivity extends Activity {
/**
* This sample demonstrates notifications with custom content views.
*
* <p>On API level 16 and above a big content view is also defined that is used for the
* 'expanded' notification. The notification is created by the NotificationCompat.Builder.
* The expanded content view is set directly on the {@link Notification} once it has been build.
* (See {@link Notification#bigContentView}.) </p>
*
* <p>The content views are inflated as {@link RemoteViews} directly from their XML layout
* definitions using {@link RemoteViews#RemoteViews(String, int)}.</p>
*/
private void createNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
//Create Intent to launch this Activity again if the notification is clicked.
Intent i = new Intent(this, CustomContentActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(this, 0, i,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(intent);
// 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);
// Cancel the notification when clicked 点击时取消通知
builder.setAutoCancel(true);
// Build the notification 构建通知
Notification notification = builder.build();
// Inflate the notification layout as RemoteViews 加载通知layout作为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
* 设置通知的内容view.因为NotificationCompatBuilder调用setContent设置content在HoneyComb工作
* 有bug,See https://code.google.com/p/android/issues/detail?id=30495,所以一般用
* notification.contentView来赋值内容view。
*/
notification.contentView = contentView;
// Add a big content view to the notification if supported. 如果支持,给通知加一个大的内容view
// Support for expanded notifications was added in API level 16. 支持扩大的通知是在api 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;
}
// notification.defaults=Notification.DEFAULT_SOUND;
// START_INCLUDE(notify)
// Use the NotificationManager to show the notification 显示通知
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(0, notification);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample_main);
}
/**
* Create and show a notification with a custom layout.
* This callback is defined through the 'onClick' attribute of the
* 'Show Notification' button in the XML layout.
*
* @param v
*/
public void showNotificationClicked(View v) {
createNotification();
}
}
对于bigContentView,可通过用两手指头平行下滑展开,折叠是上滑。对于contentView,通过notification.contentView来设置,防止以builder设置产生的bug。
其实,可以用通知的layout的作为通知的id,因为其在R文件中就是个整形常量,所以我们经常能看到mNotificationManager.cancel(R.layout.notifications),这句是取消掉id为
R.layout.notifications对应的通知。
另外,设置通知的声音与震动,通过设置notification.defaults来实现,其值为
1.Notification.DEFAULT_SOUND 仅声音
2.Notification.DEFAULT_VIBRATE 仅震动
3.Notification.DEFAULT_ALL 声音和震动
这三个值使用的是系统的声音和震动。
PendingIntent.Flag***
//PendingIntent.FLAG_ONE_SHOT表示同一个pendingIntent只能被点击打开一次
pendingIntent1 = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
//PendingIntent描述不存在,然后简单地返回null而不是创建它。下面的intent的action为haha对应的组件不存在
//所以下面pendingIntent2为空
pendingIntent2 = PendingIntent.getActivity(this, 0, new Intent("haha"), PendingIntent.FLAG_NO_CREATE);
//如果PendingIntent描述已经存在,当前应该取消之前生成一个新的
pendingIntent3 = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
//PendingIntent描述已经存在,然后保持它但它额外的数据替换成在这个新的
pendingIntent4 = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
pendingIntent1 = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
//PendingIntent描述不存在,然后简单地返回null而不是创建它。下面的intent的action为haha对应的组件不存在
//所以下面pendingIntent2为空
pendingIntent2 = PendingIntent.getActivity(this, 0, new Intent("haha"), PendingIntent.FLAG_NO_CREATE);
//如果PendingIntent描述已经存在,当前应该取消之前生成一个新的
pendingIntent3 = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
//PendingIntent描述已经存在,然后保持它但它额外的数据替换成在这个新的
pendingIntent4 = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);