Android学习:Notification的使用

本文介绍了一个简单的Android应用程序,该程序演示了如何在Android设备上发送本地通知。通过使用NotificationManager和Notification类,开发者可以轻松地为用户显示消息提醒。本文还提供了一个具体的例子,展示如何创建按钮点击事件来触发通知。

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

package com.example.notificationactivity;

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.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		Button button = (Button)findViewById(R.id.button);
		button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				addNotification();
			}
		});
	}

	/**
	 * 添加一个notification
	 */
	private void addNotification(){
		//得到NotificationManager对象
		NotificationManager notificationManager = (NotificationManager)this.
				getSystemService(Context.NOTIFICATION_SERVICE);
		//创建一个Notification实例
		Notification notification = new Notification(R.drawable.check, "催费通知", 2);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(), PendingIntent.FLAG_ONE_SHOT);
		//Notification设置最新事件信息
		notification.setLatestEventInfo(this, "你好,提醒缴费", "你已欠费100元", pendingIntent);
		//启动提醒
		notificationManager.notify(0, notification);
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值