Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android Toast 與 Notification:短暫提示與通知列訊息實作

編輯:Android 開發實例

Toast:短暫出現的提示訊息

Toast 常用來顯示短暫提示,例如「儲存成功」、「網路連線失敗」。它會在畫面上停留一段時間後自動消失,不會像 Dialog 那樣持續佔用畫面焦點。

最簡單的用法是呼叫 Toast.makeText,再呼叫 show。

Toast.makeText(context, "訊息已送出", Toast.LENGTH_SHORT).show();

若需要自訂 Toast 的版面配置,可以透過 getLayoutInflater 載入自訂 View,再使用 setView 設定到 Toast 物件中。

官方文件:Toast。

Notification:通知列訊息

Notification 用於在系統通知列顯示訊息,適合背景事件、下載完成、新訊息提醒等情境。使用 Notification 時,通常需要準備 NotificationManager、Notification 物件、PendingIntent,以及通知的標題、內容、圖示與點擊行為。

  1. 取得 NotificationManager。
  2. 建立 Notification 或 NotificationCompat.Builder。
  3. 設定圖示、標題、內容與提示方式。
  4. 建立 PendingIntent,指定點擊通知後要開啟的 Activity。
  5. 呼叫 notify 發送通知。
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.ic_launcher)
        .setContentTitle("新訊息")
        .setContentText("你有一則新的通知")
        .setContentIntent(pendingIntent);
manager.notify(1, builder.build());

若要更新通知,可以保持相同的通知 ID,再次呼叫 notify;若要取消單一通知,可使用 cancel;若要取消全部通知,可使用 cancelAll。若需要震動效果,必須在 AndroidManifest.xml 中加入 android.permission.VIBRATE 權限。

官方文件:Notification。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved