Android中的通知—Notification

本文详细介绍了Android中Notification通知的实现步骤,包括获取NotificationManager对象、初始化Notification对象、设置通知显示参数及发送通知的方法。通过具体代码示例展示了如何创建一个用于提示下载完成的通知。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android中Notification通知的实现步骤:

1.获取NotificationManager对象
NotificationManager的三个公共方法:
①cancel(int id) 取消以前显示的一个通知.假如是一个短暂的通知,试图将隐藏,假如是一个持久的通知,将从状态条中移走。
②cancelAll() 取消以前显示的所有通知。
③notify(int id,  Notification notification) 把通知持久的发送到状态条上。

2.初始化Notification对象
Notification的属性:
audioStreamType 当声音响起时,所用的音频流的类型 
contentIntent 当通知条目被点击,就执行这个被设置的Intent
contentView 当通知被显示在状态条上的时候,同时这个被设置的视图被显示
defaults 指定哪个值要被设置成默认的
deleteIntent 当用户点击"Clear All Notifications"按钮区删除所有的通知的时候,这个被设置的Intent被执行
icon 状态条所用的图片
iconLevel 假如状态条的图片有几个级别,就设置这里
ledARGB LED灯的颜色
ledOffMS LED关闭时的闪光时间(以毫秒计算) 
ledOnMS LED开始时的闪光时间(以毫秒计算) 
number 这个通知代表事件的号码 
sound 通知的声音
tickerText 通知被显示在状态条时,所显示的信息 
vibrate 振动模式
when 通知的时间戳

注:如果使Notification常驻在状态栏可以把Notification的flags属性设置为FLAG_ONGOING_EVENT

n.flags = Notification.FLAG_ONGOING_EVENT

3.设置通知的显示参数
使用PendingIntent来包装通知Intent,使用Notification的setLatestEventInfo来设置通知的标题、通知内容等信息。

4.发送通知
使用NotificationManager的notify(int id,  Notification notification)方法来发送通知。

代码(提示下载完成:)

// 通知的ID
   public static final int ID = 1;
//提醒
                
                 // 1.获取NotificationManager对象
                    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                // 2.初始化Notification对象
                    Notification n = new Notification();
                // 设置通知的icon图标
                n.icon = R.drawable.icon;
                // 设置通知在状态栏上显示的滚动信息
                n.tickerText = "下载完成";
                // 设置通知的时间
                n.when = System.currentTimeMillis();
                // 3.设置通知的显示参数
                Intent intent = new Intent(getApplicationContext(), NotificationView.class);
                PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
                n.setLatestEventInfo(getApplicationContext(), "今日头条//通知标题", "您要离线内容完成//通知内容", pi);
                // 4.发送通知
                nm.notify(ID, n);
package com.bawei.server;

import com.bawei.jinritioutiao.R;

import android.app.Activity;
import android.app.NotificationManager;
import android.os.Bundle;

public class NotificationView extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.notificationview);
    // 取消通知
    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    nm.cancel(MyServer.ID);
    finish();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值