采用Service实现本地推送通知

在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<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) 
                {
                    // 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

你可能感兴趣的:(采用Service实现本地推送通知)