Android[初级教程]第十二章 Notification的应用
这一章节,我们来学习Notification的应用,很多人问Notification是什么东东啊?我打个比方吧,还是以西游记来说:唐僧被妖怪们抓住了,那悟空得知道是哪个妖怪抓住了他师傅,他得变成一些动物(苍蝇或蚊子)去通知他师傅啊,通知唐僧悟空来救他了,这里通知就是Notification,那唐僧知道了,他就放心了,安心等着悟空来救.呵呵,让我看一下main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button android:text="通知师傅悟空来救他了" android:id="@+id/wukong"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="通知师傅八戒来救他了" android:id="@+id/bajie"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="通知师傅沙僧来救他了" android:id="@+id/shaseng"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="取消通知" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/notify_cancal"/>
</LinearLayout>
这里面没有什么特别的,只是定义了四个按钮,然后主Activity.java
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class NotificationDemo extends Activity
{
private final static int NOTIFYCATION_ID = 0x11;
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub www.zzzyk.com
super.onCreate(savedInstanceState);
setContentView(R.layout.notification);
//查找main.xml中的Button控件
Button wukong = (Button) findViewById(R.id.wukong);
wukong.setOnClickListener(new ClickEvent());
Button bajie = (Button) findViewById(R.id.bajie);
bajie.setOnClickListener(new ClickEvent());
Button shaseng = (Button) findViewById(R.id.shaseng);
shaseng.setOnClickListener(new ClickEvent());
Button notify_cancal = (Button)findViewById(R.id.notify_cancal);
notify_cancal.setOnClickListener(new ClickEvent());
}
class ClickEvent implements View.OnClickListener
{
@Override
public void onClick(View v)
{
//获取系统的NotificationManager服务
NotificationManager notifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//创建一个启动其他Activity的Intent
Intent intent = new Intent(NotificationDemo.this,
otherActivity.class);
//设置点击通知时显示内容启动的类
PendingIntent pi = PendingIntent.getActivity(NotificationDemo.this,
0, intent, 0);
//创建Notification对象
Notification notify = new Notification();
//设置Notification的发送时间
notify.when = System.currentTimeMillis();
//为Notification设置默认的声音,默认的振动,默认的闪光灯,但这些需要在AndroidManifest.xml中加入相应的权限,不然会报错
notify.defaults = Notification.DEFAULT_ALL;
switch (v.getId())
{
case R.id.wukong:
//设置Notification的图标
notify.icon = R.drawable.wukong;
//设置Notification事件信息
notify.setLatestEventInfo(NotificationDemo.this, "悟空",
"悟空来救师傅的通知", pi);
//设置Notification的文本内容,会显示在状态栏中
notify.tickerText = "悟空来救师傅了";
补充:移动开发 , Android ,