Notification 使用

Notification在android中的使用比较多,比如消息推送,使用系统的下载管理器下载,音乐播放器最小化......

现在总结一下Notificaiton的使用

[java] view plaincopy

public void initNotification() {
Intent intent = new Intent(this, ResultActivity.class);

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

/**
* getActivity(Context context, int requestCode, Intent intent, int flags)
* 这个方法的作用就相当于context.startActivity(intent)
*/
PendingIntent pendingintent = PendingIntent.getActivity(this, 0,
intent, 0);

//第二个参数表示notificaiton刚刚 显示在状态栏时候显示的文字
Notification notification = new Notification(R.drawable.ic_launcher,
"first show", 0);

RemoteViews remoteViews = new RemoteViews(getPackageName(),
R.layout.notificationlayout);

notification.contentIntent = pendingintent;

notification.contentView = remoteViews;

// Notification.FLAG_ONGOING_EVENT 设置notification显示在正在运行栏中,默认是显示在通知栏里面
notification.flags = Notification.FLAG_AUTO_CANCEL
| Notification.FLAG_ONGOING_EVENT;

NotificationManager manager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);

// 这个方法执行时候 如果该ID对象的notificaiton对象已经显示在状态栏了,那么就用新的notificaiton对象更新之前的那个
manager.notify(ID, notification);
}


这是最常见的使用方法。

android后来又出来一个NotificationCompat.Builder用来构造Notificaiton

官方网址:http://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#setProgress(int, int, boolean)

这个类提供了很多方法用于构造notificaiton。

下面是例子:

[java] view plaincopy

public void initNotificationNew() {
NotificationManager manager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);

Intent intent = new Intent(this, ResultActivity.class);

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

PendingIntent pendingintent = PendingIntent.getActivity(this, 0,
intent, 0);

RemoteViews remoteViews = new RemoteViews(getPackageName(),
R.layout.notificationlayout);

NotificationCompat.Builder builder = new NotificationCompat.Builder(
this);
//setSmallIcon setContentTitle setContentText是必须的 不定义或少定义都不显示notificaiton
builder.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("NotificationCompat")
.setContentText("NotificationCompat Text")

.setContentIntent(pendingintent).setNumber(10).setOngoing(true)
.setWhen(0).setAutoCancel(true).setContent(remoteViews);

//这个方法是显示进度条,这个比较有用
builder.setProgress(100, progress, false);

manager.notify(ID, builder.build());
}


NotificationCompat.Builder还有一个setStyle方法用于设置一个新的界面显示效果,但是好像只支持4.1+系统,使用不多。就不多说了。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值