private Notification notification;
public static final int DOWNLOAD_NOTIFICATION_ID = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 定义的渠道id
String DOWNLOAD_CHANEL_ID = "1";
// 定义的渠道名称
String DOWNLOAD_CHANEL_STRING = "下载通知";
Button mButton = findViewById(R.id.sendNotice);
// 先定义一个notificationManager
NotificationManager manager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
// 如果版本高于Android 8 需要定义个渠道
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(DOWNLOAD_CHANEL_ID, DOWNLOAD_CHANEL_STRING, NotificationManager.IMPORTANCE_HIGH);
manager.createNotificationChannel(channel);
}
// 跳转设置页面,开启通知横幅
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel1 = manager.getNotificationChannel(DOWNLOAD_CHANEL_ID);
if (channel1.getImportance() == NotificationManager.IMPORTANCE_DEFAULT) {
Intent intent2 = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
intent2.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
intent2.putExtra(Settings.EXTRA_CHANNEL_ID, DOWNLOAD_CHANEL_ID);
startActivity(intent2);
}
}
// 设置点击通知跳转
Intent intent = new Intent(this, NotificationActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
// 定义一个通知并写上对应属性
notification = new NotificationCompat.Builder(this, DOWNLOAD_CHANEL_ID)
.setContentTitle("这是一个通知标题")
//大文本
.setStyle(new NotificationCompat.BigTextStyle().bigText("上下未形,何由考之?\n" +
"冥昭瞢暗,谁能极之?\n" +
"冯翼惟象,何以识之?\n" +
"明明暗暗,惟时何为?\n" +
"阴阳三合,何本何化?\n" +
"圜则九重,孰营度之?\n" +
"惟兹何功,孰初作之?\n" +
"斡维焉系,天极焉加?"))
// .setContentText("小文本") // 小文本
// 设置超大图片
// .setStyle(new NotificationCompat.BigPictureStyle().bigPicture(BitmapFactory.decodeResource(getResources(), R.drawable.large_icon)))
// 设置小图标
.setSmallIcon(R.mipmap.ic_launcher_round)
//设置跳转
.setContentIntent(pi)
// 设置点击之后通知自动消失
// .setAutoCancel(true)
//设置大图片
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.large_icon))
.build();
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 发送通知
manager.notify(DOWNLOAD_NOTIFICATION_ID, notification);
}
});
}
Android通知的简单使用
最新推荐文章于 2024-08-04 16:46:39 发布