虽然RemoteViews可以对Notification的界面自定义,但是这里不用RemoteViews,也不用xml文件直接创建一个有进度条的Notification
package org.crazyit.notification;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* Description:
* <br/>site: <a href="http://www.crazyit.org">crazyit.org</a>
* <br/>Copyright (C), 2001-2012, Yeeku.H.Lee
* <br/>This program is protected by copyright laws.
* <br/>Program Name:
* <br/>Date:
* @author Yeeku.H.Lee kongyeeku@163.com
* @version 1.0
*/
public class NotificationTest extends Activity
{
static final int NOTIFICATION_ID = 0x1123;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Context context=getApplicationContext();
//获取应用界面中的Button对象
Button bn = (Button) findViewById(R.id.bn);
//为按钮的单击事件绑定事件监听器
bn.setOnClickListener(new View.OnClickListener()
{
@SuppressLint("NewApi")
@Override
public void onClick(View source)
{
//创建一个启动其他Activity的Intent
Intent intent = new Intent(context, OtherActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent , 0);
Notification notification =null;
if(Build.VERSION.SDK_INT > 10){
Notification.Builder builder = new Notification.Builder(context);
builder.setContentTitle("Title");
builder.setContentText("message");
builder.setSmallIcon(R.drawable.notify);
builder.setProgress(100, 38, false);//设置一个进度条
builder.setContentIntent(pendingIntent);//执行PendingIntent
notification = builder.getNotification();//将builder对象转换为普通的notification
}else{
//创建一个Notification
notification = new Notification();
//为Notification设置图标,该图标显示在状态栏
notification.icon = R.drawable.notify;
//为Notification设置文本内容,该文本会显示在状态栏
notification.tickerText = "启动其他Activity的通知";
//为Notification设置发送时间
notification.when = System.currentTimeMillis();
//为Notification设置声音
//notification.defaults = Notification.DEFAULT_SOUND;
//为Notification设置默认声音、默认振动、默认闪光灯
//notification.defaults = Notification.DEFAULT_ALL;
//notification.defaults = Notification.DEFAULT_ALL;
//设置事件信息
notification.setLatestEventInfo(context, "普通通知", "点击查看", pendingIntent);//这个函数在SDK_INT > 10的时候已经废除啦
notification.contentIntent = pendingIntent;
}
//获取系统的NotificationManager服务
NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
//发送通知
manager.notify(NOTIFICATION_ID, notification);
}
});
Button del = (Button)findViewById(R.id.del);
del.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
//获取系统的NotificationManager服务
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//取消通知
notificationManager.cancel(NOTIFICATION_ID);
}
});
}
}