Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 Service 實作本地定時通知:以遊戲體力與簽到為例

編輯:關於 Android 開發

用 Service 實作本地定時通知:以遊戲體力與簽到為例

Android 應用層的機制不少:Service、Activity 管理、Broadcast、Dialog、標題欄、狀態欄、通知、ActionBar 等等。其中通知欄(Notification)是最常被拿來做「提醒」的一塊——它就是那個可以下拉展開的列表,時不時告訴你有 App 該更新了、有人傳訊息給你了。

在遊戲裡,通知機制最典型的用途就是「按時提醒玩家回來領體力」、「提醒簽到領獎」。下面用一個 Service 搭配背景執行緒,實作一個可定時發送通知的範例。

1. 撰寫 NotificationService

設計邏輯很單純: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, "通知", "來簽到領獎了");
            }
        }
    }
}

2. 啟動服務

在需要常駐的 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);
        }
    }
}

3. 別忘了註冊

最後在 AndroidManifest.xml 中註冊這兩個元件:一個 Activity、一個 Service。

<activity android:name=".LoadingActivity" />
<service android:name=".NotificationService" />

補充一點:範例使用的是舊版的 Notification API,在新系統上請改用 NotificationCompat.Builder 搭配通知管道(NotificationChannel),並留意背景執行限制與通知權限的要求。

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