編輯:關於 Android 程式設計
消息獲取到底該用輪詢還是推送,取決於實際業務形態。如果對即時性要求高,比如微博新通知、突發新聞,那推送才是正解。但若只是普通的狀態檢測,例如每半小時或一小時檢查一次更新,輪詢其實是個很不錯的選擇——不必額外架設推送伺服器,也不用配置推送服務。
而且推送通常靠維持長連線來實作,在手機端也是要耗電的。本文要介紹的就是 Android 上實作輪詢機制最合適的工具:AlarmManager。
AlarmManager 主要用來定時或週期性地觸發某個事件,系統的鬧鐘應用就是靠它實作的,我們要用的正是它的週期執行能力。
週期任務固然可以用 Timer 和 TimerTask 實作,也可以開一個 Service 在 Thread 裡跑 while 迴圈。但最佳方案仍是 AlarmManager,原因在於 Android 的系統鎖(wakelock)機制:當系統偵測到設備閒置一段時間後,會關閉部分非必要的服務以節省資源與電力。若用 Timer 或 Service 實作,很可能螢幕熄滅一段時間後服務就被停掉,輪詢自然也跟著停擺。這一點非常容易驗證。
接下來就用 AlarmManager + Service + Thread 組出完整的輪詢服務。
public class PollingUtils {
// 開啟輪詢服務
public static void startPollingService(Context context, int seconds,
Class<?> cls, String action) {
// 獲取 AlarmManager 系統服務
AlarmManager manager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
// 包裝需要執行 Service 的 Intent
Intent intent = new Intent(context, cls);
intent.setAction(action);
PendingIntent pendingIntent = PendingIntent.getService(
context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// 觸發服務的起始時間
long triggerAtTime = SystemClock.elapsedRealtime();
// 使用 setRepeating 設置定期執行的時間間隔(seconds 秒)和需要執行的 Service
manager.setRepeating(AlarmManager.ELAPSED_REALTIME,
triggerAtTime, seconds * 1000, pendingIntent);
}
// 停止輪詢服務
public static void stopPollingService(Context context, Class<?> cls, String action) {
AlarmManager manager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, cls);
intent.setAction(action);
PendingIntent pendingIntent = PendingIntent.getService(
context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// 取消正在執行的服務
manager.cancel(pendingIntent);
}
}
public class PollingService extends Service {
public static final String ACTION = "com.ryantang.service.PollingService";
private Notification mNotification;
private NotificationManager mManager;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
initNotifiManager();
}
@Override
public void onStart(Intent intent, int startId) {
new PollingThread().start();
}
// 初始化通知欄配置
private void initNotifiManager() {
mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
int icon = R.drawable.ic_launcher;
mNotification = new Notification();
mNotification.icon = icon;
mNotification.tickerText = "New Message";
mNotification.defaults |= Notification.DEFAULT_SOUND;
mNotification.flags = Notification.FLAG_AUTO_CANCEL;
}
// 彈出 Notification
private void showNotification() {
mNotification.when = System.currentTimeMillis();
// 點擊通知標題後跳轉到新 Activity
Intent i = new Intent(this, MessageActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
mNotification.setLatestEventInfo(this,
getResources().getString(R.string.app_name),
"You have new message!", pendingIntent);
mManager.notify(0, mNotification);
}
/**
* 模擬向 Server 輪詢的異步線程
*/
int count = 0;
class PollingThread extends Thread {
@Override
public void run() {
System.out.println("Polling...");
count++;
// 當計數能被 5 整除時彈出通知
if (count % 5 == 0) {
showNotification();
System.out.println("New message!");
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
System.out.println("Service:onDestroy");
}
}
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 啟動輪詢服務
System.out.println("Start polling service...");
PollingUtils.startPollingService(this, 5, PollingService.class, PollingService.ACTION);
}
@Override
protected void onDestroy() {
super.onDestroy();
// 停止輪詢服務
System.out.println("Stop polling service...");
PollingUtils.stopPollingService(this, PollingService.class, PollingService.ACTION);
}
}
把輪詢掛在 Activity 的 onDestroy 裡取消,只適合演示用途;正式專案中通常會希望輪詢在應用退到背景後仍然持續,這時應把啟動與停止的時機交由更長生命週期的元件(例如開機廣播接收器或 JobScheduler / WorkManager)來管理。另外,從 Android 4.4 起 setRepeating 的精度會被系統刻意降低以達到電力最佳化,若對時間精度有要求,需要改用 setExact 系列 API 並搭配 AlarmManager.setExactAndAllowWhileIdle。最後别忘了在清單檔註冊 Service。
Android 實作本地上傳圖片並設定為圓形頭像
先把本地圖片上傳到伺服器,再根據 URL 把頭像處理成圓形。因為上傳圖片用到了 bmob 平台,所以要先到 bmob(https://www.bmob.cn)申請密鑰。
Android 手把手打造精美的用戶登入介面
這篇要帶大家一步一步打造一個類似下圖那樣的登入 UI 介面:一、準備圖片資源先把需要用到的圖示(如 Facebook、LinkedIn 的連線按鈕)放進 drawable
Buzz 桌面教學:怎麼換掉應用程式圖示
Buzz 桌面的一大特色,就是可以隨心更換程式的圖示。嫌官方設計醜、或是早就看膩了,那就換一個。圖示來源不限,自己做的、網友分享的都能用。以下說明操作。 Buzz 桌面更
dumpsys 使用指南:用一行命令看清 Android 系統服務的狀態
一、dumpsys 是什麼 dumpsys 執行在裝置上,能輸出各項系統服務的當前狀態。官方描述是「The dumpsys tool runs on the device