Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 采用Service實現本地推送通知

采用Service實現本地推送通知

編輯:關於Android編程

在android的應用層中,涉及到很多應用框架,例如:Service框架,Activity管理機制,Broadcast機制,對話框框架,標題欄框架,狀態欄框架,通知機制,ActionBar框架等等。

經常會使用到通知機制中的通知欄框架(Notificaiton),它適用於交互事件的通知。它是位於頂層可以展開的通知列表。它會時不時的提醒你什麼軟件該更新了,什麼人發你微信消息了等。

我主要用於記錄於,按時來領取體力啊,來登錄領獎啊,這個在游戲中用途比較廣泛

1.寫一個類NotificationService繼承Service

功能邏輯:啟動一個線程,定時檢查是否要發送領取獎勵,體力了,我這邊由於涉及到公司東西,寫的是簡單的demo,只判斷了時間點,就發送通知,實際游戲中可能根據是否已經領取過,多少等級,啟動多久之後等條件,有問題可以共同討論。

代碼:

package com.test.service;

import java.util.Calendar;
import java.util.List;

import android.R;
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 NotificationService m_service = null;
    private NotificationManager m_notificationMgr = null;
    private NotifyThread m_notifyThread = null;
    
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        
        m_service = this;
        m_notificationMgr = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        
        if(m_notificationMgr == null)
        {
            Log.i(TAG, "NotificationService noticationMgr null");
        }
        m_notifyThread = new NotifyThread();
        m_notifyThread.start();
        
        Log.i(TAG, "NotificationService onCreate...");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        
        Log.i(TAG, "NotificationService onStartCommand...");
        
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        
        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)
        {
            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);
            //Intent intent = new Intent(this, LoadingActivity.class);
            //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            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)
        {
            List 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) 
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
            Log.i(TAG, "NotifyThread stop...");
        }
        
        public void checkNotify()
        {
            Calendar cal = Calendar.getInstance();
            int hour = cal.get(Calendar.HOUR_OF_DAY);
            //int minute = cal.get(Calendar.MINUTE);
            //int second = cal.get(Calendar.SECOND);
            
            //Log.i(TAG, "hour:" + hour + "m:" + minute + "s:" + second);
            
            if((hour >= 12 && hour < 14) || (hour >= 18 && hour <20))
                m_service.notify(GET_STAMINA_ID, "通知", "來這領取你的體力了");
            
            if(hour == 20)
                m_service.notify(PUNCH_CARD_ID, "通知", "來這簽到領獎了");
        }
    }
}

2.寫個啟動服務的代碼

package com.test.service;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import org.cocos2dx.lib.Cocos2dxActivity;

public class GameActivity extends Cocos2dxActivity {

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        startService();
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }
    
    public void startService()
    {
        if(!NotificationService.isRunning(this))
        {
            Intent startIntent = new Intent(this, 
        NotificationService.class);
            startService(startIntent);
        }
    }
}

需要在AndroidManifest.xml注冊這兩個類,一個Activity,一個Service

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved