刘关张三人在孔明的指导下,针对Android开发进行着魔鬼训练。
这天晚上,关羽、张飞都已睡了。刘备兴致勃勃的拿着新写的代码找到孔明,孔明接过刘备的代码,展开竹简,一片一片地仔细阅读。一边审阅一边点头,“嗯,有进步有进步,字写得也清楚了,编译也能顺利通过了……”
刘备挠了挠头,“嘿嘿,这也是这段时间努力的结果。”
孔明说:“不过你很多代码写得还是不太规范,代码规范还是很重要的。命名还可以,但是一些该转下一行写的地方都写到一行去了,看着很不整齐,很不专业。不要怕费竹简嘛,反正我屋里多的是,随便拿去用就好了!”
刘备说:“其实有一个问题我一直想问军师。”
孔明说:“主公请问。”
刘备说:“孔明家境貌似不错哇,不知是祖上继承下来的吗?”
孔明说:“主公好直白,直接就问财产问题,不知道的还以为是查税呢。我不是什么富二代啦,你也知道,我做开发很长时间了,之前成功开发过一两款还算火爆的产品和网站,所以有些积蓄,在这里结庐而居,倒也悠闲。”
刘备感叹道:“孔明真是少年有成啊,唉,啥时候我们三兄弟也能像你那样功成收山。”
孔明说:“主公请放心,我夜观星象,主公未来之成就必远在我之上,将来必有一番惊天地之伟业。我现在来辅佐主公也只是顺水推舟而已。”
刘备怀疑道:“孔明多次说夜观星象,星象真的能预示人的前程吗?”
孔明微笑道:“天机不可泄露,此事只看主公如何想,有时觉得老天也是个程序员,而我们就是一个一个的计算单元。其实比起天道,人心更加重要。只有自己相信自己,坚守自己的行事之道,事情总会水到渠成。主公表面嘻嘻哈哈,内心却比常人更加坚韧,能忍常人之不能忍,所以我才更加相信主公以后必有大成。”
刘备:“哈哈,我的优点被大家发现了!谢谢大家多年来的支持与鼓励!哇哈哈哈!”
诸葛亮:“我能收回刚才的话吗……”
1.1. Notification介绍
Notification是Android进行消息提示的重要方式,它是看不见的程序组件例如,Broadcast Receiver、Service和不活跃的Activity用于警示用户有事件发生的最好途径。Notification一般用于对电话、短信、邮件、闹钟这些事件进行消息提示。当事件发生时,在手机的状态条上就会出现一个小图标,提示用户处理这个快讯。
1.1.1.Notification的常用方法
Notification的构造方法为:
Notification(inticon, CharSequence tickerText, long when)
l icon:将要显示在状态条上图标的资源id;
l tickerText:当Notification第一次启动时显示在状态条上的文字;
l when:通知显示的时间点,使用System.currentTimeMillis()方法可以立刻显示。
在Android 3.0版本后,Android引入了Notification.builder构造器来创建Notification对象,Notification.builder提供了多种方法用来设置Notification的图标、内容、提示声音等,如下表12-1所示:
表12-1 Notification.builder的常用方法
常用方法 | 说明 |
build() | 生成一个配置好的Notification的实例。 |
addAction(int icon, CharSequence title, PendingIntent intent) | 为Notification添加一个动作。 |
setAutoCancel(boolean autoCancel) | 当autoCancel为true时,Notification会自动消失,反之亦然。 |
setContentIntent(PendingIntent intent) | 当Notification被点击时,将触发这个PendingIntent。 |
setTicker(CharSequence tickerText) | 设置Notification通知面板中的tickerText。 |
setContentTitle(CharSequence title) | 设置Notification通知面版中的Title。 |
setContentText(CharSequence text) | 设置Notification通知面板中的Text。 |
setLargeIcon(Bitmap icon) | 为Notification的通知面板添加一个大图标。 |
setSmallIcon(int icon) | 为Notification的通知面板添加一个小图标。 |
setSound(Uri sound, int streamType) | 为Notification添加声音,参数为sound的Uri地址,也可以通过参数streamType使用自定义的流类型设置声音。 |
setStyle(Notification.Style style) | 设置Notification的风格。 |
setVibrate(long[] pattern) | 设置震动。 |
setWhen(long when) | 设置通知时间。通知面板依据时间排序通知条。 |
setOngoing(boolean ongoing) | 设置该通知是否是持续不断的,持续不断的通知有如下特征: 1.处于正在进行的服务面板,在正常通吃面板的上方; 2.不允许出现“X”关闭按钮,并且清除全部对其毫无作用。 |
setOnlyAlertOnce(boolean onlyAlertOnce) | 当onlyAlertOnce被设置为true时,Notification只被播放一次,即声音、震动、条状通知将只出现一次。 |
下面是一个利用Notification.builder构造器创建一个接收邮件的Notification:
Notificationnotification= new Notification.Builder()
.setContentTitle("New mail from " + sender.toString())
.setContentText(subject)
.setSmallIcon(R.drawable.new_mail)
.setLargeIcon(aBitmap)
.build();
setTicker()方法是在Notification播放时用于设置在状态栏上滚动的字幕,如果很长,会自动分割滚动;setContentTitle()方法用于设置Notification展开后的标题;setContentText()方法用于设置Notification展开后的内容。它们的效果如图12-1和图12-2所示:
图12-1setTicker()方法
图12-2setContentTitle()和setContentText()的效果
1.1.2.PendingIntent的介绍
注意到上一小节的Notification.builder构造器中提供了setContentIntent(PendingIntent intent)这个方法,该方法使用了PendingIntent而不是Intent作为参数。
PendingIntent和Intent有些区别。首先,Intent是及时启动的,随所在的Activity 消失而消失。PendingIntent是对Intent的包装,可以理解为延迟执行的Intent,用于处理即将发生的事件,例如,Notification中使用PendingIntent延迟跳转界面。
可以通过PendingIntent.getActivity(Context context, int requestCode, Intentintent, int flags)方法从系统中获取PendingIntent,该方法返回的PendingIntent可以用于启动一个Activity;通过PendingIntent.getBroadcast(Context context, int requestCode,Intent intent, int flags) 方法用于从系统中获取一个PendingIntent对象,用于向BroadcastReceiver发送Intent;通过PendingIntent. getService(Context context, int requestCode, Intentintent, int flags) 方法从系统获取一个PendingIntent对象,用于启动一个Service。
PendingIntent的两个主要的方法如下所示:
l public void send ():该方法主要用于触发PendingIntent的Intent行为,通过参数中的Intent启动一个Activity、Service,或向BroadcastReceiver发送一个Intent。
l public void cancel ():该方法用于取消一个已经触发了的PendingIntent。只有PengdingIntent的源应用程序才有权限调用cancel()方法把它从系统中移除掉。
1.1.3.Notification常用设置介绍
Notification通常通过设置Notification的成员变量来改变通知显示的效果,主要有以下8个常用的的设置:
l Notification.icon:用于显示Notification的图标,可以通过调用Notification.builder的setLargeIcon(Bitmapicon)和setSmallIcon(inticon)两个方法来设置显示的图标。
l Notification.contentIntent :用于设置PendingIntent对象,点击Notification时发送Intent。
l Notification.defaults:添加默认的通知效果。Android为该defaults字段提供了4个常量,分别为:
n DEFAULT_ALL:使用所有默认值;
n DEFAULT_LIGHTS :使用默认闪光提示;
n DEFAULT_SOUNDS :使用默认提示声音;
n DEFAULT_VIBRATE:使用默认手机震动。
l Notification.flags:设置状态标志位flags,Andorid为该flags字段提供了7个主要的常量,分别为:
n FLAG_AUTO_CANCEL:表示该通知能被状态栏的清除按钮给清除掉;
n FLAG_NO_CLEAR:表示该通知不能被状态栏的清除按钮给清除掉;
n FLAG_ONGOING_EVENT:表示该通知正在运行;
n FLAG_INSISTENT:表示通知是否一直显示;
n FLAG_ONLY_ALTER_ONCE:设置每次提示通知时发出提示音或振动;
n FLAG_SHOW_LIGHT:设置每次提示通知时打开LED提示灯;
n FLAG_FOREGROUND_SERVICE:设置该通知为目前运行的后台服务。
l Notification.priority:设置Notification的优先级,根据此优先级影响其在通知列表中的顺序。Android为priority字段提供了五个不同的优先级,从高到低分别是:PRIORITY_HIGH、PRIORITY_MAX、PRIORITY_DEFAULT、PRIORITY_MIN和PRIORITY_LOW,默认为PRIORITY_DEFAULT。
l
孔明:如果想要让声音持续重复直到用户对通知做出反应,可以在Notification的flags字段增加“FLAG_INSISTENT”。
|
Notification.sound:设置Notification的提示音。
l Notification.vibrate:设置振动提示,具体代码如下所示:
long[] vibrate = {0,100,200,300};
Notification.vibrate = vibrate;
其中long数组用于定义成想要的任何长度,{0,100,200,300}表示0毫秒后开始振动,振动100毫秒后停止,再过200毫秒后再次振动300毫秒。
孔明:当使用DEFAULT_VIBRATE添加手机震动时,需加在AndroidManifest.xml中加入权限:<uses-permission android:name="android.permission.VIBRATE" />
|
l 设置LED灯:可以自定义通知的LED提醒模式,代码如下所示:
notification.ledARGB = 0xff00ff00;(这里设置LED的颜色为绿色)
notification.ledOnMS = 300;
notification.ledOffMS = 1000;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
其中ledARGB用于设置LED灯的颜色;ledOnMS用于设置LED开始时的闪光时间(以毫秒计算);ledOffMS用于设置LED关闭时的闪光时间。
1.2. NotificationManager介绍
NotificationManager是所有通知的管理类,负责发送通知、清除通知等操作。NotificationManager支持Toast和Notification两种通知方式,前者相当于一个定时关闭的对话框,后者在状态栏上显示一条消息。Toast和Notification都可以随时取消。NotificationManager不能实例化,可以通过getSystemService(String)方法来获得,代码如下所示:
String service =Context.NOTIFICATION_SERVICE;
NotificationManagernm = (NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);
NotificationManager有三个常用方法:
l public void cancel(int id):表示该通知能被状态栏的清除按钮给清除掉;
l public void cancelAll():移除所有已经显示的通知;
l public void notify(int id, Notification notification):提交一个通知在状态栏中显示。如果拥有相同标签和相同id的通知已经被提交而且没有被移除,该方法会更新之前的通知。
1.3. Notification实例
小飞飞和小羽羽都编写了不少实例,作为大哥的我,不能落后,这一节中,我要首先给出Notification的实现步骤,然后实现Notification的例子,震撼震撼他们!
1.3.1.Notification的实现步骤
在详细介绍了Notification的类、成员变量和方法之后,本节将要介绍如何使用Notification。具体步骤如下:
1. 获取NotificationManager对象
String service = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager=(NotificationManager)getSystemService(service);
2. 初始化Notification对象
//实例化Notification
Notification notification = new Notification();
3. 设置通知的显示参数
// 设置显示图标,该图标会在状态栏显示
int icon =R.drawable.happy;
// 设置显示提示信息,该信息也在状态栏显示
String tickerText = "测试Notification";
// 显示时间
long when = System.currentTimeMillis();
notification.icon = icon;
notification.tickerText = tickerText;
notification.when = when;
4. 调用setLatestEventInfo()方法设置视图中的图标和时间
// 实例化Intent
Intent intent = new Intent(MainActivity.this, MainActivity.class);
// 获得PendingIntent
PendingIntent pIntent = PendingIntent.getActivity(MainActivity.this,0, intent, 0);
// 设置事件信息
notification.setLatestEventInfo(MainActivity.this,"Title", "Content", pIntent);
5. 发出通知
//Notification标示ID
private static final int ID = 1;
//发出通知
mNotificationManager.notify(ID, n);
1.3.2.自定义状态栏通知
大哥我要使用Notification创建一个状态栏通知,用于通知二弟,三弟吃饭。新建一个Android项目,在layout布局文件夹中编写布局文件main.xml,代码如下所示:
main.xml代码清单12-3-2:
<!--小备备:我要做一名厨师表演艺术家。-->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#EEE"
android:textStyle="bold"
android:textSize="25sp"
android:text="Notification应用的小案例" />
<Button
android:id="@+id/btnSend"
android:text="sendnotification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
该文件中设置了一个Button,用来触发Notification。继续建立一个布局文件second.xml,用于设置点击Notification触发的Activity的布局,其代码如下所示:
second.xml代码清单12-3-2:
<!--小羽羽:我要做一名歌唱女艺术家。-->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#EEE"
android:textStyle="bold"
android:textSize="25sp"
android:text="谢谢使用Notification!" />
</LinearLayout>
接着,建立一个Activity 类,命名为SimpleNotification,代码如下所示:
SimpleNotification.java代码清单12-3-2:
/**
* @author张飞:你拿的什么?
刘备:我妈给带的鸡蛋。
张飞:给我吃。
刘备:不给……你猜,猜有几个。你要猜出来我把这两个都给你。
张飞:五个?
*/
public class SimpleNotification extends Activity {
private PendingIntent mContentIntent =null;
private Notification mNoti = null;
private Button mButton = null;
@Override
public void onCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mButton= (Button) findViewById(R.id.btnSend);
finalNotificationManager mNotificationManager =(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
//跳转到SecondActivity
IntentnotificationIntent = new Intent(this,SecondActivity.class);
mContentIntent= PendingIntent.getActivity(SimpleNotification.this, 0, notificationIntent, 0);
Notification.BuildernotiBuilder = newNotification.Builder(this);
//设置展开后的内容
notiBuilder.setContentText("Warning");
notiBuilder.setWhen(System.currentTimeMillis());
//设置图标
notiBuilder.setSmallIcon(R.drawable.face_surprise);
notiBuilder.setContentIntent(mContentIntent);
//设置展开后的标题
notiBuilder.setContentTitle("GetContent");
//获取Notification实例
mNoti=notiBuilder.getNotification();
//设置声音
mNoti.defaults=Notification.DEFAULT_SOUND;
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//当点击Button后,显示Notification
mNotificationManager.notify(0,mNoti);
}
});
}
}
当点击Notification时将触发SecondActivity,其代码如下所示:
SecondActivity.java代码清单12-3-2:
public class SecondActivity extends Activity {
@Override
protected void onCreate(BundlesavedInstanceState) {
//TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
}
}
运行程序,结果如图12-3所示:
图12-3程序的开始界面
当点击“send notification”按钮时,状态条上将出现小图标,向下拖动小图标,出现如图12-4所示的界面:
图12-4拖动Notification图标后出现的界面
点击“GetContent”按钮后将进入 SecondActivity,结果如图12-5所示:
图12-5跳转到SecondActivity界面
1.3.3.同时显示多个Notification
大哥我左通知下,右通知下,这二弟,三弟怎么还不来吃饭,莫非要我使出同时通知多个Notification,二弟,三弟才能来吃饭。新建一个Android项目,创建一个Activity类,命名为MultiNotification,代码如下所示:
MultiNotification.java代码清单12-3-3:
/**
* @author张飞:龙虾,海蟹,哈哈!我就爱吃带壳的!
刘备:服务员,给他来盘瓜子!
*/
public class MultiNotification extends Activity {
private PendingIntent mContentIntent =null;
private Notification mNoti = null;
private Button mBtn = null;
@Override
public void onCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mBtn= (Button) findViewById(R.id.btnSend);
mBtn.setOnClickListener(new OnClickListener() {
publicvoid onClick(View v) {
//第一个Notification
AddNoti(1);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//第二个Notification
AddNoti(2);
}
});
}
public void AddNoti(int ID){
//获取NotificationManager
NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
//跳转到SecondActivity
Intent notificationIntent = new Intent(this,SecondActivity.class);
//通知系统允许替代当前的Notification
mContentIntent= PendingIntent.getActivity(SimpleNotification.this, ID, notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
Notification.BuildernotiBuilder = newNotification.Builder(this);
//设置展开后的内容
notiBuilder.setContentText("Warning");
notiBuilder.setWhen(System.currentTimeMillis());
//设置图标
notiBuilder.setSmallIcon(R.drawable.face_surprise);
notiBuilder.setContentIntent(mContentIntent);
//设置展开后的标题
notiBuilder.setContentTitle("GetContent");
//获取Notification实例
mNoti=notiBuilder.getNotification();
//表示该通知能被状态栏的清除按钮给清除掉
mNoti.flags= Notification.FLAG_AUTO_CANCEL;
//设置声音
mNoti.defaults=Notification.DEFAULT_SOUND;
//当点击Button后,显示Notification
mNotificationManager.notify(ID,mNoti);
}
}
接着,创建SecondActivity.java文件并在layout布局文件夹中创建布局文件main.xml和second.xml,其代码和12.3.2节相同。运行程序,结果如图12-6所示:
图12-6多个Notification界面
1.4. 玄德有话说
刘备:军师,什么情况下使用Notification呢?
孔明:Notification通常用于后台运行的应用程序对用户进行消息提醒。Notification目前被各大应用厂商广泛使用,作为消息提醒的重要方式。不过,滥用Notification也会造成了用户体验变差。所以最好在应用程序中谨慎使用Notification,并且提供设置接口,使用户可以自行开关通知功能。