編輯:Android 開發實例
與 AlarmManager 相應的,系統中還有一個名為 AlarmManagerService 的服務程式,它才是真正提供鬧鈴能力的角色。這支服務負責維護各應用程式註冊下來的鬧鈴,並在恰當的時刻把即將觸發的鬧鈴交給鬧鈴裝置(在系統底層,這個由 Linux 實作的裝置名為「/dev/alarm」),同時持續監聽該裝置。一旦有鬧鈴觸發或事件發生,AlarmManagerService 便會遍歷鬧鈴清單、找到對應的註冊項並發出廣播。這支服務在系统啟動時由 system_server 拉起,並完成鬧鈴裝置的初始化。值得一提的是,在 Java 層的 AlarmManagerService 與 Linux 的 Alarm 驅動之間,還隔著一層 JNI 封裝。
AlarmManager 把應用與服務職責分離之後,開發者便不必關心底層實作細節,只需透過 AlarmManager 就能使用這項服務——這或許正是客戶端/伺服器模式的價值所在。AlarmManager 與 AlarmManagerService 之間透過 Binder 溝通,兩者是多對一的關係。
在 Android 系統中,AlarmManager 提供了 3 個介面、5 種鬧鈴類型。
void cancel(PendingIntent operation)void set(int type, long triggerAtTime, PendingIntent operation)void setRepeating(int type, long triggerAtTime, long interval, PendingIntent operation)void setTimeZone(String timeZone)ELAPSED_REALTIME(系統值 3):當系統進入睡眠時,此類型鬧鈴不會喚醒裝置,須待下次甦醒後才會送出。它採用相對時間,從開機後開始計時(含睡眠時間),可透過 SystemClock.elapsedRealtime() 取得。ELAPSED_REALTIME_WAKEUP(系統值 2):用法同上,但具備喚醒系統的能力。RTC(系統值 1):睡眠時不會喚醒系統,採用絕對時間(UTC),可透過 System.currentTimeMillis() 取得。RTC_WAKEUP(系統值 0):用法同 RTC,但能喚醒系統。POWER_OFF_WAKEUP(系統值 4):一種關機鬧鈴,即使在關機狀態下也能喚醒系統,用法同 RTC 類型。PendingIntent 值得特別留意。它相當於 Intent 的進階封裝,既承載了 Intent 的描述,又負責其行為的執行。若把 Intent 比喻成一張訂單,那麼 PendingIntent 更像是一位「下單的人」:既要負責把訂單送出去,也要處理送達後的後續——例如成功後準備驗收、失敗後決定重送或取消。開發者可透過以下三種方式取得 PendingIntent 實例:
getBroadcast():取得的 PendingIntent 會扮演廣播的角色,效果等同呼叫 Context.sendBroadcast(),並在 Intent 中攜帶接收者資訊。getActivity():取得的 PendingIntent 可直接啟動一個新的 Activity,等同 Context.startActivity()。若要讓新 Activity 獨立於當前進程,需在 Intent 中加上 Intent.FLAG_ACTIVITY_NEW_TASK。getService():取得的 PendingIntent 可直接啟動 Service,等同 Context.startService()。// getBroadcast 用法 Intent intent = new Intent(AlarmController.this, OneShotAlarm.class); PendingIntent sender = PendingIntent.getBroadcast(AlarmController.this, 0, intent, 0); // getActivity 用法 PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, AlarmService.class), 0); // getService 用法 mAlarmSender = PendingIntent.getService(AlarmService.this, 0, new Intent(AlarmService.this, AlarmService_Service.class), 0);
/Chapter08_Broadcast_AlarmManager/src/com/amaker/ch08/app/MainActivity.java
package com.amaker.ch08.app;
import com.amaker.ch08.app.R;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* 測試 AlarmManager
*/
public class MainActivity extends Activity {
// 聲明 Button
private Button setBtn, cancelBtn;
// 定義廣播 Action
private static final String BC_ACTION = "com.amaker.ch08.app.action.BC_ACTION";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 設置當前布局視圖
setContentView(R.layout.main);
// 實例化 Button
setBtn = (Button) findViewById(R.id.Button01);
cancelBtn = (Button) findViewById(R.id.Button02);
// 獲得 AlarmManager 實例
final AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
// 實例化 Intent
Intent intent = new Intent();
// 設置 Intent action 屬性
intent.setAction(BC_ACTION);
intent.putExtra("msg", "你該去開會啦!");
// 實例化 PendingIntent
final PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this, 0,
intent, 0);
// 獲得系統時間
final long time = System.currentTimeMillis();
// 設置按鈕單擊事件
setBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 重復提示,從當前時間開始,間隔5秒
am.setRepeating(AlarmManager.RTC_WAKEUP, time,
8 * 1000, pi);
}
});
// 設置按鈕單擊事件
cancelBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
am.cancel(pi);
}
});
}
}
/Chapter08_Broadcast_AlarmManager/src/com/amaker/ch08/app/MyReceiver.java
package com.amaker.ch08.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 獲得提示信息
String msg = intent.getStringExtra("msg");
// 顯示提示信息
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
}
}
/Chapter08_Broadcast_AlarmManager/res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:text="設置鬧鐘" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> <Button android:text="取消鬧鐘" android:id="@+id/Button02" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> </LinearLayout>
/Chapter08_Broadcast_AlarmManager/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.amaker.ch08.app" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".MainActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name="MyReceiver"> <intent-filter> <action android:name="com.amaker.ch08.app.action.BC_ACTION"/> </intent-filter> </receiver> </application> <uses-sdk android:minSdkVersion="3" /> </manifest>
Android 教學:用程式碼實作常用佈局
關於 Android 常用佈局,利用 XML 檔實作的範例已經很多。那麼該如何用程式碼來實作呢?雖然純用程式碼佈局沒有太大必要、也不太被鼓勵,但我認為透過程式碼實作這些佈
Android 開發實戰:整合百度地圖 SDK 完整指南
百度地圖 Android SDK 讓開發者能夠輕鬆存取百度地圖服務與資料,打造功能豐富、互動性強的 LBS(位置服務)應用。它提供地圖顯示、定位、搜尋等一整套能力,且所有
Android 表單字段驗證的實例代碼詳解
在登錄、註冊這類表單場景中,字段驗證是必不可少的一環——用戶名不能為空、郵箱格式要正確、手機號要合法等。借助開源的 Android-Validator 庫,我們能優雅地完
第三方 App 接入微信平台實研究(二):通訊時序與回調機制
微信開放平台推出後,大量第三方應用希望接入其中,原因不難理解:能直接借用微信既有的社交關係鏈來傳播自己的內容,省下自建社交體系的大量成本。我在實習期間研究了這套接入流程,