系统服务-----NotificationManager

本文详细介绍了如何在Android应用中使用通知API实现自定义通知。包括获取通知管理器、创建PendingIntent、设置通知样式等内容,并提供了完整的代码示例。

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

熟悉api事例笔记:

package com.test;

import com.example.test.R;

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.Bundle;
import android.view.View;

public class MainActivity extends Activity {
	private static final int NOTIFICATION_FLAG = 1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	}

	public void notificationMethod(View view) {
		// 在Android进行通知处理,首先需要从系统哪里获得通知管理器NotificationManager,它是一个系统Service。
		NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		switch (view.getId()) {
		case R.id.btn1:
			 // 创建一个PendingIntent,和Intent类似,不同的是由于不是马上调用,需要在下拉状态条出发的activity,所以采用的是PendingIntent,即点击Notification跳转启动到哪个Activity
			PendingIntent pi = PendingIntent.getActivity(this,0,new Intent(this,MainActivity.class),0);
			Notification notyfi1 = new Notification();
			notyfi1.icon = R.drawable.ic_launcher;
			notyfi1.tickerText = "您有一天新消息请注意查收 ";
			notyfi1.when = System.currentTimeMillis();
			notyfi1.flags |= Notification.FLAG_AUTO_CANCEL;// FLAG_AUTO_CANCEL表明当通知被用户点击时,通知将被清除。
			notyfi1.number = 1;
			notyfi1.setLatestEventInfo(this, "标题", "内容", pi);
			//通过通知管理器来发起通知。如果id不同,则每click,在statu那里增加一个提示
			nm.notify(NOTIFICATION_FLAG,notyfi1);
			break;

		default:
			break;
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值