使用通知管理者 NotificationManager
package com.itheima.notification;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;public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void click(View view){ //获取系统的服务 通知管理者 NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); //第一参数 通知的图标 //第二参数 通知文本 //第三参数 通知时间 Notification notification = new Notification(R.drawable.notification, "我是一个通知", System.currentTimeMillis()); //设置点击之后会自动取消掉通知 notification.flags = Notification.FLAG_AUTO_CANCEL; //目的,也就是点击通知之后会发生的事情 Intent intent = new Intent(); intent.setAction(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:110")); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0); //设置下拉通知之后显示的通知的标题和内容 notification.setLatestEventInfo(this, "我是标题", "我是内容", contentIntent); //发一个通知 第一参数是给通知编号,方便以后删除等管理,不写就直接0 nm.notify(0, notification); } /** * 新版本的notification * @param view */ @SuppressLint("NewApi") public void click2(View view){ //为了兼容旧的版本 这个不怎么推荐使用 Notification noti = new Notification.Builder(this) //设置标题 .setContentTitle("我是标题") //设置内容 .setContentText("我是内容") //设置小图标 .setSmallIcon(R.drawable.notification) //设置大图标 .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher)) .build(); //通过管理器显示出来 NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); nm.notify(0, noti); }}