100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > Android中使用Notification在状态栏上显示通知

Android中使用Notification在状态栏上显示通知

时间:2021-05-27 12:11:33

相关推荐

Android中使用Notification在状态栏上显示通知

场景

状态栏上显示通知效果

注:

博客:

/badao_liumang_qizhi

关注公众号

霸道的程序猿

获取编程相关电子书、教程推送与免费下载。

实现

新建NotificationActivity,通过getSystemService方法获取通知管理器。

然后创建通知并设置通知的一些属性,再使用通知管理器发送通知。

package com.badao.relativelayouttest;import androidx.annotation.RequiresApi;import androidx.appcompat.app.AppCompatActivity;import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.content.Intent;import android.os.Build;import android.os.Bundle;public class NotificationActivity extends AppCompatActivity {final int NOTIFYID = 0x123; //通知的ID@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_notification);//新建通知管理器final NotificationManager notificationManager =(NotificationManager) getSystemService(NOTIFICATION_SERVICE);// 创建一个Notification对象Notification.Builder notification = new Notification.Builder(this);// 设置打开该通知,该通知自动消失notification.setAutoCancel(true);// 设置通知的图标notification.setSmallIcon(R.drawable.dog);// 设置通知内容的标题notification.setContentTitle("还不赶紧关注公众号");// 设置通知内容notification.setContentText("点击查看详情!");//设置使用系统默认的声音、默认震动notification.setDefaults(Notification.DEFAULT_SOUND| Notification.DEFAULT_VIBRATE);//设置发送时间notification.setWhen(System.currentTimeMillis());// 创建一个启动其他Activity的IntentIntent intent = new Intent(NotificationActivity.this, DetailActivity.class);PendingIntent pi = PendingIntent.getActivity(NotificationActivity.this, 0, intent, 0);//设置通知栏点击跳转notification.setContentIntent(pi);//发送通知notificationManager.notify(NOTIFYID, notification.build());}}

点击详情时跳转到DetailActivity,设计详情页,显示文本信息

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="/apk/res/android"xmlns:app="/apk/res-auto"xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".DetailActivity"><TextViewandroid:layout_width="wrap_content"android:text="霸道的程序猿"android:layout_height="wrap_content"/></LinearLayout>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。