Android -- Notification,如何向通知栏发送通知,点击通知开启相应的Activity

本文提供了一个关于Android中使用新旧API实现通知功能的例子。通过两个不同的方法展示了如何为4.1及更高版本系统创建通知,包括设置图标、标题、内容等。

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

1. 示例代码: 新老API之分, 新的API必须API16以后 4.1以后的系统

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

@SuppressLint("NewApi") public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	/**
	 * 旧版本的notification
	 * 
	 * @param view
	 */
	public void click1(View view) {
		//1.获取系统通知的管理者
		 NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		//2.初始化一个notification的对象
		 Notification notification = new Notification(R.drawable.notification, "我是滚动的文本",  System.currentTimeMillis() );
 
		//3.设置notification的具体参数
		 notification.flags = Notification.FLAG_AUTO_CANCEL;
		 
		 //注意:细节
		// notification.contentView = 自定义的notification view
		 
		// notification.sound = Uri.parse(uriString);
		// notification.vibrate = new long[]{100,200,100}; //消息弹出震动100震动时间 200 间隔时间,需要权限
		 Intent intent = new Intent();
		 intent.setAction(Intent.ACTION_VIEW);
		 intent.setData(Uri.parse("http://www.baidu.com"));
		 PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
		 notification.setLatestEventInfo(this, "我是大的标题", "我是标题下面的内容", contentIntent);
		 //4.直接把消息给 notification的管理者
		 nm.notify(0, notification);
	}

	/**
	 * 新版notification的写法.
	 * @param view
	 */
	public void click2(View view){
		 Intent intent = new Intent();
		 intent.setAction(Intent.ACTION_VIEW);
		 intent.setData(Uri.parse("http://www.baidu.com"));
		 PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
		
		
		//1.获取系统通知的管理者
		 NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		//2.用notification工厂 创建一个notification
		 Notification noti = new Notification.Builder(this)
         .setContentTitle("我是大的标题")
         .setContentText("我是内容")
         .setSmallIcon(R.drawable.notification)
         .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
		 .setContentIntent(contentIntent)
         .build();
		//3.把notification显示出来
		 nm.notify(1, noti);
	}
	
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值