由于版本问题,通知可能显示不出来。。
两个活动,Main主活动用来显示通知,Detail用来显示通知详细内容
两个布局文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".DetailActivity"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/b" /> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> </LinearLayout>
两个java文件
package com.example.mynotifyi; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class DetailActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); } }
package com.example.mynotifyi; import androidx.appcompat.app.AppCompatActivity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import android.os.Bundle; import java.util.prefs.NodeChangeEvent; public class MainActivity extends AppCompatActivity { final private int NOTIFYID = 0x123; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //创建并发送通知 //获得系统服务的通知管理器 NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); //获得一个通知Builder对象 Notification.Builder builder = new Notification.Builder(MainActivity.this); builder.setAutoCancel(true);//设置通知打开后自动消失 // builder.setSmallIcon(R.drawable.b);//通知图标 builder.setContentTitle("通知标题"); builder.setContentText("通知内容"); builder.setWhen(System.currentTimeMillis());//设置发送时间 builder.setDefaults(Notification.DEFAULT_SOUND| Notification.DEFAULT_VIBRATE);//设置默认声音,振动 //创建一个启动详细页面的Intent对象 Intent intent = new Intent( MainActivity.this,DetailActivity.class ); //创建可以由其他应用程序在稍晚进行出发的Intent机制,即让Detail在点击了消息后再触发 PendingIntent pi = PendingIntent.getActivity( MainActivity.this,0,intent,0 ); builder.setContentIntent(pi);//设置通知栏点击跳转 //通知管理器发送通知 notificationManager.notify(NOTIFYID,builder.build()); } }