編輯:關於 Android 開發
Android 應用層的機制不少:Service、Activity 管理、Broadcast、Dialog、標題欄、狀態欄、通知、ActionBar 等等。其中通知欄(Notification)是最常被拿來做「提醒」的一塊——它就是那個可以下拉展開的列表,時不時告訴你有 App 該更新了、有人傳訊息給你了。
在遊戲裡,通知機制最典型的用途就是「按時提醒玩家回來領體力」、「提醒簽到領獎」。下面用一個 Service 搭配背景執行緒,實作一個可定時發送通知的範例。
設計邏輯很單純:Service 啟動後開一條執行緒,每隔一段時間檢查一次是否該發通知。範例只判斷時間點就發送,實務上通常還要搭配「今天是否已領取」、「玩家等級」、「距離上次登入多久」等條件一起判斷。
package com.test.service;
import java.util.Calendar;
import java.util.List;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class NotificationService extends Service {
private static final String TAG = "TAG";
private static final int CHECK_TICK = 1 * 60 * 1000; // 每分鐘檢查一次
private static final int GET_STAMINA_ID = 1; // 領體力通知
private static final int PUNCH_CARD_ID = 2; // 簽到通知
private NotificationManager m_notificationMgr = null;
private NotifyThread m_notifyThread = null;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
m_notificationMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (m_notificationMgr == null) {
Log.i(TAG, "notificationMgr null");
}
m_notifyThread = new NotifyThread();
m_notifyThread.start();
Log.i(TAG, "NotificationService onCreate...");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "NotificationService onStartCommand...");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.i(TAG, "NotificationService onDestroy...");
if (m_notifyThread != null) {
m_notifyThread.stopThread();
}
super.onDestroy();
}
public void notify(int notifyId, String strTitle, String strMsg) {
if (m_notificationMgr == null) {
return;
}
Notification localNotification = new Notification();
localNotification.icon = R.id.icon;
localNotification.defaults = Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND;
localNotification.when = System.currentTimeMillis();
localNotification.tickerText = strMsg;
ComponentName componentName = new ComponentName(this, LoadingActivity.class);
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setComponent(componentName);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
localNotification.setLatestEventInfo(this, strTitle, strMsg, pendingIntent);
m_notificationMgr.notify(notifyId, localNotification);
}
/** 判斷服務是否已在執行 */
public static boolean isRunning(Context context) {
ActivityManager activityMgr = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (activityMgr == null) {
return false;
}
List<ActivityManager.RunningServiceInfo> serviceList = activityMgr.getRunningServices(50);
if (serviceList.isEmpty()) {
return false;
}
for (int i = 0, n = serviceList.size(); i < n; ++i) {
if (serviceList.get(i).service.getClassName()
.toString().equals("com.jthd.marsX.NotificationService")) {
return true;
}
}
return false;
}
private class NotifyThread extends Thread {
private boolean m_bStop = false;
public synchronized void stopThread() {
m_bStop = true;
}
@Override
public void run() {
Log.i(TAG, "NotifyThread run...");
while (!m_bStop) {
checkNotify();
try {
sleep(CHECK_TICK);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.i(TAG, "NotifyThread stop...");
}
public void checkNotify() {
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY);
// 中午與傍晚提醒領取體力
if ((hour >= 12 && hour < 14) || (hour >= 18 && hour < 20)) {
notify(GET_STAMINA_ID, "通知", "來領取你的體力了");
}
// 晚間八點提醒簽到
if (hour == 20) {
notify(PUNCH_CARD_ID, "通知", "來簽到領獎了");
}
}
}
}
在需要常駐的 Activity(例如遊戲主畫面)中啟動它,並先判斷是否已在執行,避免重複啟動:
package com.test.service;
import android.content.Intent;
import android.os.Bundle;
import org.cocos2dx.lib.Cocos2dxActivity;
public class GameActivity extends Cocos2dxActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService();
}
public void startService() {
if (!NotificationService.isRunning(this)) {
Intent startIntent = new Intent(this, NotificationService.class);
startService(startIntent);
}
}
}
最後在 AndroidManifest.xml 中註冊這兩個元件:一個 Activity、一個 Service。
<activity android:name=".LoadingActivity" /> <service android:name=".NotificationService" />
補充一點:範例使用的是舊版的 Notification API,在新系統上請改用 NotificationCompat.Builder 搭配通知管道(NotificationChannel),並留意背景執行限制與通知權限的要求。
Android 實戰筆記:Facebook 與 Twitter 分享功能的接入全流程
從需求到上線:兩週搞定社群分享 年初的時候,公司英文版 App 丟來一個新需求:把 Facebook 和 Twitter 的分享能力補進去。整個功能從技術預研、方案比選到
Android 原生側滑菜單實作:Toolbar 與 DrawerLayout 的簡單做法
Android 原生側滑菜單實作:Toolbar 與 DrawerLayout 的簡單做法 在許多 App 中,側滑菜單是常見的導覽方式。相較於額外引入第三方庫,Andr
高仿京東商城 Android 客戶端源碼分享:完整可運行的電商骨架
想動手做一個電商 App,卻不知道從哪裡下手?一份結構完整的商城客戶端源碼,往往比十篇教學更能說明問題。這份高仿京東風格的 Android 專案,把首頁推薦、分類、購物車
Git 版本控制工具(二):本地版本庫的常用操作詳解
Git 版本控制工具(二):本地版本庫的常用操作詳解 在上一章節中,我們學習了 Git 最基本的用法,包括安裝、創建版本庫與提交本地代碼。本章將介紹更多實用技巧。首先建立