日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

信息提醒之Notification,兼容全部SDK-更新中

發(fā)布時間:2025/3/21 编程问答 59 豆豆
生活随笔 收集整理的這篇文章主要介紹了 信息提醒之Notification,兼容全部SDK-更新中 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

概述

Notification與對話框、Toast無論從外觀上還是從使用方法上有本質(zhì)的區(qū)別。
Notification是Android中很理想的提示方法,Notification可以在Android桌面上最上方的狀態(tài)欄顯示提示信息,還可以顯示圖像,甚至可以將控件加載到上面,而且只要用戶不清空,這些信息可以永久的保留在狀態(tài)欄,除了這些還有其他更吸引人的特性,讓我們一起發(fā)掘下吧。

本篇博文中使用的創(chuàng)建Notification 是通過一個兼容全部SDK的工具類創(chuàng)建的,因為setLatestEventInfo方法在API11中不建議使用了,而且谷歌在API23 (Android6.0)中徹底廢棄了該方法。

所以本篇博文中會提供一個創(chuàng)建Notification的工具類,來兼容所有額SDK版本~

NotificationUtils.java

import android.annotation.TargetApi; import android.app.Notification; import android.app.PendingIntent; import android.content.Context; import android.os.Build;import com.apkfuns.logutils.LogUtils;import java.lang.reflect.Method;/*** 兼容所有SDK的NotificationUtil** @author Mr.Yang on 2016-02-18 20:34.* @version 1.0* @desc*/ public class NotificationUtil {public static Notification createNotification(Context context, PendingIntent pendingIntent, String title, String text, int iconId) {Notification notification;if (isNotificationBuilderSupported()) {LogUtils.d("isNotificationBuilderSupported");notification = buildNotificationWithBuilder(context, pendingIntent, title, text, iconId);} else {// 低于API 11 HoneycombLogUtils.d("buildNotificationPreHoneycomb");notification = buildNotificationPreHoneycomb(context, pendingIntent, title, text, iconId);}return notification;}public static boolean isNotificationBuilderSupported() {try {return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) && Class.forName("android.app.Notification.Builder") != null;} catch (ClassNotFoundException e) {return false;}}@SuppressWarnings("deprecation")private static Notification buildNotificationPreHoneycomb(Context context, PendingIntent pendingIntent, String title, String text, int iconId) {Notification notification = new Notification(iconId, "", System.currentTimeMillis());try {// try to call "setLatestEventInfo" if availableMethod m = notification.getClass().getMethod("setLatestEventInfo", Context.class, CharSequence.class, CharSequence.class, PendingIntent.class);m.invoke(notification, context, title, text, pendingIntent);} catch (Exception e) {// do nothing}return notification;}@TargetApi(Build.VERSION_CODES.HONEYCOMB)@SuppressWarnings("deprecation")private static Notification buildNotificationWithBuilder(Context context, PendingIntent pendingIntent, String title, String text, int iconId) {android.app.Notification.Builder builder = new android.app.Notification.Builder(context).setContentTitle(title).setContentText(text).setContentIntent(pendingIntent).setSmallIcon(iconId);if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {return builder.build();} else {return builder.getNotification();}}}

在狀態(tài)欄上顯示通知信息

Notification需要使用NotificationManager來管理,一般來講創(chuàng)建并顯示Notification需要以下5個步驟:

  • 通過getSystemService方法獲取一個NotificationManager對象
  • 創(chuàng)建一個Notification對象,在這里我們使用兼容較好的NotificationUtils類來創(chuàng)建
  • 由于Notification可以與應(yīng)用程序脫離,也就是說,即使應(yīng)用程序被關(guān)閉,Notification仍然會顯示在狀態(tài)欄中,當(dāng)應(yīng)用程序再此啟動后,又可以重新控制這些Notification,如清除或者替換他們。因此,需要創(chuàng)建一個PendingIntent對象。該對象由Android系統(tǒng)負(fù)責(zé)維護(hù),因此在應(yīng)用程序關(guān)閉后,該對象仍然不會被釋放。
  • 使用Notification類的setLatestEventInfo方法設(shè)置詳細(xì)信息(改方法已經(jīng)在6.0廢棄,可使用提供的工具類來代替)
  • 使用NotificationManager類的notify方法顯示Notification。再這一步需要指定標(biāo)識Notification的唯一ID,改ID必須相對于同一個NotificationManager對象是唯一的,否則就會覆蓋相同ID的Notification。
  • /*** 全部兼容* http://blog.csdn.net/yangshangwei/article/details/50688221*/private void showNotification() {notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, getIntent(), 0);// 工具類判斷版本,通過不同的方式獲取NotificationNotification notification = NotificationUtil.createNotification(this, pendingIntent, "您有新消息", "消息內(nèi)容", R.drawable.flag_mark_blue);notification.tickerText = "我是提示通知時的文字內(nèi)容";notification.when = System.currentTimeMillis();// 使用默認(rèn)的聲音notification.defaults = Notification.DEFAULT_SOUND;// 使用默認(rèn)的震動 需要添加uses-permission android.permission.VIBRATEnotification.defaults = Notification.DEFAULT_VIBRATE;// 使用默認(rèn)的Lightnotification.defaults = Notification.DEFAULT_LIGHTS;// 所有的都是用默認(rèn)值notification.defaults = Notification.DEFAULT_ALL;notificationManager.notify(R.drawable.flag_mark_blue, notification);// 5S后,執(zhí)行取消的方法,即5S后 自動清除該通知欄 ,根據(jù)需求考慮是否需要這樣 // Handler handler = new Handler(); // handler.postDelayed(new Runnable() { // @Override // public void run() { // notificationManager.cancel(R.drawable.flag_mark_blue); // } // },5*1000);}

    上述代碼中的

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, getIntent(), 0);

    返回一個PendingIntent對象,這個對象與一個Activity對象關(guān)聯(lián),這個案例中與當(dāng)前的Activity關(guān)聯(lián)。將Android狀態(tài)欄滑下來后,單擊Notification,就會顯示關(guān)聯(lián)的這個Activity。如果Activity已經(jīng)顯示,仍然會顯示一個新的Activity,并覆蓋當(dāng)前顯示的Activity。不過這些顯示的Activity都是一樣的,除了getActivity方法之外,還可以getBroacast和getService方法。 這兩個方法用于單擊Notification后發(fā)出一條廣播或者啟動一個服務(wù)。

    設(shè)置默認(rèn)發(fā)聲、震動、Light效果

    // 使用默認(rèn)的聲音notification.defaults = Notification.DEFAULT_SOUND;// 使用默認(rèn)的震動 需要添加uses-permission android.permission.VIBRATEnotification.defaults = Notification.DEFAULT_VIBRATE;// 使用默認(rèn)的Lightnotification.defaults = Notification.DEFAULT_LIGHTS;// 所有的都是用默認(rèn)值notification.defaults = Notification.DEFAULT_ALL;

    注意事項:

    • defaults屬性必須在調(diào)用notify方法之前調(diào)用,否則不起作用
    • 設(shè)置震動效果需要在AndroidManifest.xml中添加權(quán)限
    • <uses-permission android:name="android.permission.VIBRATE" />

    清除指定的Notification

    如果要清除某個消息可以使用NotificationManager.cancel方法,該方法只有一個參數(shù),表示要清除的Notification的ID。

    case 1:// 清除指定的Notification-cancel(id)cancelNotification(R.drawable.flag_mark_blue); /*** 清除某個消息,** @param id Notification的id*/private void cancelNotification(int id) {notificationManager.cancel(id);}

    清除全部的Notification

    使用cancelAll()可以清除當(dāng)前NotificationManager對象中的所有的Notification。


    清除Notification后觸發(fā)的善后工作

    當(dāng)我們將狀態(tài)欄下拉下來之后都會看到在屏幕的右上角有一個“清除“按鈕或者圖標(biāo),單擊該按鈕可以清除所有的Notification, 那么在清除后,往往需要做一些善后的工作,這個就需要通過Notification.deleteIntent來完成。

    deleteIntent也需要設(shè)置一個PendingIntent類型的變量,由于在清除所有的Notification時調(diào)用,可以將這個動作和Activity、Broadcast、Service關(guān)聯(lián)。

    private void notificationDeleteIntent() {// 通過getSystemservice獲取NotificationManagernotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);// PendingIntent --getAct ,getBrc ,getSev等等PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity_.class), 0);// NotificationNotification notification = NotificationUtil.createNotification(this, pendingIntent, "Title", "text", R.drawable.tag_blue);notification.when = System.currentTimeMillis();notification.tickerText = "清除Notificaiton的善后工作";// 清除通知,觸發(fā)的操作,這里將清除Notification觸發(fā)的deleteIntent設(shè)置為跳轉(zhuǎn)到ToastDemoListAct,當(dāng)然了也可以啟動廣播 服務(wù)等等PendingIntent deleteIntent = PendingIntent.getActivity(this, 0, new Intent(this, ToastDemoListAct.class), 0);notification.deleteIntent = deleteIntent;notificationManager.notify(R.drawable.tag_blue, notification);}

    如果想響應(yīng)刪除動作的Activity傳遞數(shù)據(jù),可以利用被PendingIntent封裝的intent。例如

    ...... Intent intent = new Intent(this,Main.class); //傳遞數(shù)據(jù) intent.putExtra("msg","what r u doing ?");PendingIntent pendingIntent = PendingIntent.getActivity(this,0.intent,0); .......

    這樣在Activity中(一般在onCreate方法中)接收解即可

    String msg = getIntent().getStringExtra("msg"); .........

    永久存在的Notification

    我們發(fā)現(xiàn)單擊”清除“按鈕,有些Notification并沒有被清除掉,這樣無法被清除的Notification被稱為永久Notification,這些Notification只能通過他們的程序 來清除。

    實現(xiàn)這樣的效果很簡單,只需要設(shè)置Notification.flag即可。

    /*** FLAG_SHOW_LIGHTS //控制閃光* <p/>* FLAG_ONGOING_EVENT //顯示在”正在運行的“一欄中* <p/>* FLAG_INSISTENT //重復(fù)發(fā)出聲音,直到用戶響應(yīng)此通知* <p/>* FLAG_ONLY_ALERT_ONCE //標(biāo)記聲音或者震動一次* <p/>* FLAG_AUTO_CANCEL //在通知欄上點擊此通知后自動清除此通知* <p/>* FLAG_NO_CLEAR //將flag設(shè)置為這個屬性那么通知欄的那個清楚按鈕就不會出現(xiàn)* <p/>* FLAG_FOREGROUND_SERVICE//前臺服務(wù)標(biāo)記* <p/>* https://developer.android.com/intl/zh-cn/reference/android/app/Notification.html#FLAG_GROUP_SUMMARY* <p/>* FLAG_GROUP_SUMMARY* <p/>* FLAG_LOCAL_ONLY*/private void permanentNotification() {// 通過getSystemService獲取NotificationManagernotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);// PendingIntentPendingIntent pendingIntent = PendingIntent.getActivity(this, 0, getIntent(), 0);// NotificationNotification notification = NotificationUtil.createNotification(this, pendingIntent, "Title", "Content", R.drawable.face);notification.tickerText = "清除不掉的Notification";notification.when = System.currentTimeMillis();notification.flags = Notification.FLAG_NO_CLEAR;// 展示NotificationnotificationManager.notify(R.drawable.face, notification);}

    自定義Notification

    我們可以通過Notification.contentView 來自定義Notification。

    contentView 并不是一個View,而是RemoteViews類型。

    RemoteView只支持有限的幾個控件和布局,如下所示

    RemoteView支持的布局

    • FrameLayout
    • LinearLayout
    • RelativeLayout

    RemoteView支持的控件

    • AnalogClock
    • Button
    • Chronometer
    • ImageButton
    • ImageView
    • ProgressBar
    • TextView

    如果使用其他控件,會拋出異常。

    實現(xiàn)步驟

    activity_custom_notification.xml

    <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical"><TextView android:id="@+id/textview"android:layout_width="fill_parent"android:layout_height="wrap_content"android:gravity="center"android:text="自定義內(nèi)容"android:textColor="#F00"android:textSize="20sp" /><ImageView android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:src="@drawable/tag_green" /></LinearLayout> private void customNotification() {// 通過getSystemService()獲取NotificationManagernotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);//PendingIntentPendingIntent pendingIntent = PendingIntent.getActivity(this,0,getIntent(),0);// NotificationNotification notification = NotificationUtil.createNotification(this,pendingIntent,"Title","text",R.drawable.flag_mark_yellow);// 設(shè)置屬性...notification.tickerText="自定義Notification";notification.when = System.currentTimeMillis();//自定義Notification布局RemoteViews remoteViews = new RemoteViews(getPackageName(),R.layout.activity_custom_notification);remoteViews.setTextViewText(R.id.textview,"666666666");notification.contentView = remoteViews ;// notifiynotificationManager.notify(R.drawable.flag_mark_yellow,notification);}

    運行效果


    大拿總結(jié)的,可以參考

    總結(jié)

    以上是生活随笔為你收集整理的信息提醒之Notification,兼容全部SDK-更新中的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。