Android中使用Notification在状态栏上显示通知
生活随笔
收集整理的這篇文章主要介紹了
Android中使用Notification在状态栏上显示通知
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
場景
狀態(tài)欄上顯示通知效果
?
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
關(guān)注公眾號
霸道的程序猿
獲取編程相關(guān)電子書、教程推送與免費下載。
實現(xiàn)
新建NotificationActivity,通過getSystemService方法獲取通知管理器。
然后創(chuàng)建通知并設(shè)置通知的一些屬性,再使用通知管理器發(fā)送通知。
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);// 創(chuàng)建一個Notification對象Notification.Builder notification = new Notification.Builder(this);// 設(shè)置打開該通知,該通知自動消失notification.setAutoCancel(true);// 設(shè)置通知的圖標(biāo)notification.setSmallIcon(R.drawable.dog);// 設(shè)置通知內(nèi)容的標(biāo)題notification.setContentTitle("還不趕緊關(guān)注公眾號");// 設(shè)置通知內(nèi)容notification.setContentText("點擊查看詳情!");//設(shè)置使用系統(tǒng)默認的聲音、默認震動notification.setDefaults(Notification.DEFAULT_SOUND| Notification.DEFAULT_VIBRATE);//設(shè)置發(fā)送時間notification.setWhen(System.currentTimeMillis());// 創(chuàng)建一個啟動其他Activity的IntentIntent intent = new Intent(NotificationActivity.this, DetailActivity.class);PendingIntent pi = PendingIntent.getActivity(NotificationActivity.this, 0, intent, 0);//設(shè)置通知欄點擊跳轉(zhuǎn)notification.setContentIntent(pi);//發(fā)送通知notificationManager.notify(NOTIFYID, notification.build());} }點擊詳情時跳轉(zhuǎn)到DetailActivity,設(shè)計詳情頁,顯示文本信息
<?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"android:orientation="vertical"tools:context=".DetailActivity"><TextViewandroid:layout_width="wrap_content"android:text="霸道的程序猿"android:layout_height="wrap_content"/></LinearLayout>?
總結(jié)
以上是生活随笔為你收集整理的Android中使用Notification在状态栏上显示通知的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android中使用AlertDialo
- 下一篇: Android中点击按钮启动另一个Act