編輯:關於 Android 程式設計
狀態欄通知(Notification)是 Android 中相當實用的一項功能,以下由淺入深帶你完整掌握。
1、Notification 是顯示在手機狀態欄的通知——狀態欄位於螢幕最上方,一般會顯示網路狀態、電池狀態、時間等資訊。
2、Notification 代表一種具有全域效果的通知,程式通常透過 NotificationManager 服務來發送。
3、NotificationManager 是位於應用程式框架層的重要系統服務,應用程式可透過它向系統發送全域通知。
4、透過 Notification.Builder 類別,開發者能更輕鬆地建立 Notification 物件。
5、Notification.Builder 提供的常用方法如下:
① setDefaults():設定通知的 LED 燈、音樂、震動等,支援 DEFAULT_SOUND(預設聲音)、DEFAULT_VIBRATE(預設震動)、DEFAULT_LIGHTS(預設閃光燈)與 ALL(全部)。
② setAutoCancel():設定點擊通知後自動從狀態欄移除。
③ setContentTitle():設定通知標題。
④ setContentText():設定通知內容。
⑤ setSmallIcon():設定通知的小圖示。
⑥ setLargeIcon():設定通知的大圖示。
⑦ setTicker():設定通知在狀態欄的提示文字。
⑧ setContentIntent():設定點擊通知後要啟動的元件對應的 PendingIntent。
6、發送 Notification 的步驟:
① 呼叫 getSystemService(NOTIFICATION_SERVICE) 取得 NotificationManager 服務;
② 透過 Builder 建立 Notification 物件;
③ 為 Notification 設定各種屬性;
④ 透過 NotificationManager 發送通知。
7、存取系統功能須加上權限,例如操作閃光燈需 flashlight 權限、操作震動器需 vibrate 權限。
8、若要啟動另一個頁面,別忘了在 AndroidManifest.xml 中聲明該 Activity。
9、具體程式碼如下:
package org.crazyit.ui;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
public class NotificationTest extends Activity {
private static final int NOTIFICATION_ID = 0x123;
private NotificationManager nm;
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//取得系統的 NotificationManager 服務
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
//發送通知的按鈕事件
public void send(View source) {
Intent intent = new Intent(NotificationTest.this, OtherActivity.class);
PendingIntent pi = PendingIntent.getActivity(NotificationTest.this, 0, intent, 0);
Notification notify = new Notification.Builder(this)
.setAutoCancel(true) //點擊後自動消失
.setTicker("有新消息") //狀態欄提示文字
.setSmallIcon(R.drawable.notify) //通知圖示
.setContentTitle("一條新通知") //內容標題
.setContentText("恭喜你,您加薪了,工資增加20%!") //通知內容
.setSound(Uri.parse("android.resource://org.crazyit.ui/" + R.raw.msg)) //自訂聲音
.setWhen(System.currentTimeMillis())
.setContentIntent(pi) //點擊後要啟動的 Intent
.getNotification();
nm.notify(NOTIFICATION_ID, notify); //發送通知
}
//刪除通知的按鈕事件
public void del(View v) {
nm.cancel(NOTIFICATION_ID); //取消通知
}
}
以上就是狀態欄通知從建立、設定到發送與取消的完整用法,掌握 Builder 的設定項目後,就能靈活地為應用加入各式通知提醒。
Android Scroller 原理與實作:打造 ListView 側滑菜單
在 Android 中,若直接使用 scrollTo 或 scrollBy 移動 View,過程通常是瞬間完成,使用者體驗較差。Scroller 的作用就是讓位移具備過渡
ViewPager 基本用法詳解:PagerAdapter、標題欄與 TabHost 效果實現
概述 ViewPager 是 Android 3.0 之後引入的 UI 控件(視圖滑動切換工具)。它的能力很單純:透過手勢左右滑動完成 View 的切換,通常用來做 Ap
把 Android 模組打成 jar 並用 ProGuard 混淆的實操筆記
又是一個睡不著的夜裡,來處理一件拖了很久的事:專案裡有部分程式碼想對外提供成 jar,而且不希望被人直接反編譯看光光。 步驟一:打包 jar 在 Eclipse 中
Android 自動完成輸入:AutoCompleteTextView 與 MultiAutoCompleteTextView
搜索框、收件人輸入框這類場景,都需要在用戶敲字的同時給出候選提示。Android 提供了兩個現成控件來滿足需求。 AutoCompleteTextView:輸入時弹出下