Android中使用Notification在狀態欄上顯示通知


場景

狀態欄上顯示通知效果

 

 

注:

博客:
https://blog.csdn.net/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)
    @Override
    protected 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的Intent
        Intent 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="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">

    <TextView
        android:layout_width="wrap_content"
        android:text="霸道的程序猿"
        android:layout_height="wrap_content"/>

</LinearLayout>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM