使用Timer、AlarmManager实现定时服务+Notification进行模拟推送的实现


作者:laozhao666更新于 05月06日访问( 514)评论( 0

近来公司要实现推送,现在大部分公司都没有实力实现假设自己的推送服务器,这里只能使用定时服务,定时从服务器上获取到最新消息,废话不说上代码。

AndroidManifest.xml 配置代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.alarmtest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.alarmtest.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
         <activity
            android:name="com.example.alarmtest.MessageActivity"
         >
        </activity>
         <!-- 为此应用私有的独立进程 -->  
        <service android:process=":AlarmSysService" android:name="com.example.alarmtest.AlarmSysService"></service>  
        <!-- 为此应用私有的独立进程 -->  
        <service android:process=":MyPushService" android:name="com.example.alarmtest.MyPushService"></service>
       <!-- 为此应用私有的独立进程 -->  
        <service  android:process=":PushService" android:name="com.example.alarmtest.PushService"></service>
        <!-- 监听系统启动广播 -->
        <receiver android:name="com.example.alarmtest.AlarmReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"></action>
                <category android:name="android.intent.category.LAUNCHER"></category>
            </intent-filter>
        </receiver>           
    </application>

</manifest>

AlarmSysService 主要实现代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
    public void doAlarmTask(){
        if(null==alarm){
            alarm=(AlarmManager)getSystemService(ALARM_SERVICE);
            Intent intent =new Intent(AlarmSysService.this, AlarmReceiver.class);
            intent.setAction(ACTION);
            PendingIntent sender=PendingIntent.getBroadcast(AlarmSysService.this, 0, intent, 0);
            //早上9点
            startDate = Util.getTaskStartTime(this);
            //当天早上9点开始执行任务,重复执行是从第二天开始执行早上9点
            alarm.setRepeating(AlarmManager.RTC_WAKEUP, startDate.getTime(),1*24*60*60*1000+startDate.getTime(), sender);
        }
    }

AlarmReceiver 广播接收器

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
    private final static String TAG="AlarmReceiver";
    private final static String SYSTEM_BROADCAST_ACTION="android.intent.action.BOOT_COMPLETED";
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(PushService.ACTION)) {
            Toast.makeText(context, "short alarm", Toast.LENGTH_LONG)
                    .show();
            Intent mintent = new Intent(context, PushService.class);
            Logger.i(TAG, "------------接收到【定时时钟】发出的广播并将进行消息轮循查询提示!");
            context.startService(mintent);
        } 
        if(intent.getAction().equals(SYSTEM_BROADCAST_ACTION)){
            Logger.i(TAG, "接收到【系统启动】后发出的广播,开始启动服务!");
            context.startService(new Intent(context,AlarmSysService.class));
            context.startService(new Intent(context,MyPushService.class));
        }
    }
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
public class PushService extends Service {
    private final static String TAG="PushService";
    private Date startDate = null;
    private Date endDate = null;
    private int doTaskDay=1;//周一执行
    public final static String ACTION="cn.com.action.MyAction";
    private MessageNotification mMessageNotification;

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //周一执行
        doTaskDay=Integer.parseInt(this.getString(R.string.doTaskDate));
        checkServiceStatus();
        mMessageNotification=MessageNotification.getInstance(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        doTask();
        return super.onStartCommand(intent, flags, startId);
    }


    private void doTask() {
        // 每周周一早上9点
        startDate = Util.getTaskStartTime(this);
        endDate= Util.getTaskEndTime(this);
        new Thread(){
            @Override
            public void run() {
                try{
                    Logger.i(TAG, Util.getLongTimeToDateTime(startDate.getTime())+"------------【定时闹钟】定时任务开始执行消息提示!");
                        //Log.i("FyPullService", "任务 来了 ");
                        int weekDay = Util.getDayOfWeek();
                        int d = weekDay - 1;
                        //Log.i("FyPullService", "weekDay=" + weekDay + "今天是周= " + d);
                        /*Log.i("FyPullService", "设定时间=" + startDate.getTime() + "--系统时间="
                                + System.currentTimeMillis()+"结束时间="+endDate.getTime());*/
                        //周一  注意:每一周的第一天从周日开始
                        //Log.i(TAG,"weekDay=="+(doTaskDay+1));
                        if (weekDay ==(doTaskDay+1)){//System.currentTimeMillis()
                            Long n=System.currentTimeMillis();//Util.getCurrentTime();
                            Long s=startDate.getTime();
                            Long e=endDate.getTime();
                            if(n-s>=0&&e-n>=0){
                                doTaskGetMessage(); 
                            }
                        } 
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
            }
        }.start();
    }


    private void doTaskGetMessage(){
        Logger.i(TAG, "------------根据【定时时钟】定时任务进行消息提示!");
        //从服务器获取到的bookId 从服务器上更新的小说通知id保存和提示的
        int bookId=123456;
        //默认是1000 提醒状态 改变条件
        int status=mMessageNotification.getNotificationStatus();
        int nbookId=mMessageNotification.getNotificationBookId();
        if(nbookId!=bookId||status==mMessageNotification.getNotificationID()){
            Log.i(TAG, TAG+"开始执行任务了 ");
            /**
             * 从服务器上获取到消息
             */
            String tickerText="您好,有新消息!";
            String title="有新消息提示";
            String content="有最新........消息已经发布,请随时关注";
            String mbookId=""+bookId;
            String perChapterId="1233";
            String chapterId="1234";
            mMessageNotification.getNotification(tickerText,title,content,mbookId,perChapterId,chapterId);
            int nid=mMessageNotification.getNotificationID();
            //Log.i(TAG, "nid=="+nid);
            mMessageNotification.resetNotificationStatus();
            //bookId++;
        }
    }

    //该功能是为了防止服务被杀死,故意开启2个服务,不论哪个服务被强制回收,也可以重新开启服务
    private void checkServiceStatus() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    String filePath = "com.example.alarmtest.FyPushService";
                    boolean flag = Util.isServiceRunning(PushService.this,filePath);
                    if (flag == false) {
                        PushService.this.startService(new Intent(PushService.this,MyPushService.class));
                    }
                    String _filePath = "com.example.alarmtest.PushService";
                    boolean _flag= Util.isServiceRunning(PushService.this,_filePath);
                    if (_flag == false) {
                        PushService.this.startService(new Intent(PushService.this,PushService.class));
                    }
                } catch (Exception e) {

                }
            }
        }.start();

    }


    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
public class MyPushService extends Service {
    private final static String TAG="FyPushService";
    private TimerTask task = null;
    private Timer timer = null;
    private Date startDate = null;
    private Date endDate = null;
    private int doTaskDay=1;//周一执行
    private boolean isRunning = true;

    private MessageNotification mMessageNotification;
    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //周一执行
        doTaskDay=Integer.parseInt(this.getString(R.string.doTaskDate));
        checkServiceStatus();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mMessageNotification=MessageNotification.getInstance(this);
        doTask();
        return super.onStartCommand(intent, flags, startId);
    }

    private void doTask() {
        timer = new Timer();
        // 每周周一早上9点
        startDate = Util.getTaskStartTime(this);
        endDate= Util.getTaskEndTime(this);
        task = new TimerTask() {
            @Override
            public void run() {
                try{
                    Logger.i(TAG, Util.getLongTimeToDateTime(startDate.getTime())+"------------【定时器】定时任务开始执行消息提示!");
                        //Log.i("FyPullService", "任务 来了 ");
                        int weekDay = Util.getDayOfWeek();
                        int d = weekDay - 1;
                        //Log.i("FyPullService", "weekDay=" + weekDay + "今天是周= " + d);
                        /*  Log.i("FyPullService", "设定时间=" + startDate.getTime() + "--系统时间="
                                + System.currentTimeMillis()+"结束时间="+endDate.getTime());*/
                        //周一  注意:每一周的第一天从周日开始
                        //Log.i(TAG,"weekDay=="+(doTaskDay+1));
                        if (weekDay ==(doTaskDay+1)){//System.currentTimeMillis()
                            Long n=System.currentTimeMillis();//Util.getCurrentTime();
                            Long s=startDate.getTime();
                            Long e=endDate.getTime();
                            if(n-s>=0&&e-n>=0){
                                doTaskGetMessage(); 
                            }
                        } 
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
            }
        };
        timer.schedule(task, startDate, 1*24*60*60*1000); // 7*24*60*60*1000
    }




    private void doTaskGetMessage(){
        Logger.i(TAG, "------------根据定时器定时任务进行消息提示!");
        //从服务器获取到的bookId 从服务器上更新的通知id保存和提示的
        int bookId=123456;
        //默认是1000 提醒状态 改变条件
        int status=mMessageNotification.getNotificationStatus();
        int nbookId=mMessageNotification.getNotificationBookId();
        if(nbookId!=bookId||status==mMessageNotification.getNotificationID()){
            Log.i(TAG, TAG+"开始执行任务了 ");
            /**
             * 从服务器上获取到消息
             */
            String tickerText="您好,有新消息!";
            String title="有新消息提示";
            String content="有最新........消息已经发布,请随时关注";
            String mbookId=""+bookId;
            String perChapterId="1233";
            String chapterId="1234";
            mMessageNotification.getNotification(tickerText,title,content,mbookId,perChapterId,chapterId);
            int nid=mMessageNotification.getNotificationID();
            //Log.i(TAG, "nid=="+nid);
            mMessageNotification.resetNotificationStatus();
            //bookId++;
        }
    }





    private void checkServiceStatus() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    String filePath = "com.example.alarmtest.MyPushService";
                    boolean flag = Util.isServiceRunning(MyPushService.this,filePath);
                    if (flag == false) {
                        MyPushService.this.startService(new Intent(MyPushService.this,MyPushService.class));
                    }
                    String _filePath = "com.example.alarmtest.PushService";
                    boolean _flag= Util.isServiceRunning(MyPushService.this,_filePath);
                    if (_flag == false) {
                        MyPushService.this.startService(new Intent(MyPushService.this,PushService.class));
                    }
                } catch (Exception e) {

                }
            }
        }.start();

    }

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

}```

这里分别使用了AlarmManagerTimerTimerTask 来实现,
**区别:AlarmManager只在规定的时间点执行一次,如果网络临时出现断网,推送消息将不会再执行。
TimerTimerTask 可以设定在规定的时间段内进行多次的从服务器上获取数据,直到成功,成功后设置标识不让该线程进行运行即可。**
可以点击下载推送demo,如果发现有什么问题,请及时回帖或者发邮件1305913633@qq.com
eoe找不到上传附件的地方,大家感兴趣可以到csdn上下载
http://download.csdn.net/detail/zhaozhen666/5335164

声明:eoe文章著作权属于作者,受法律保护,转载时请务必以超链接形式附带如下信息

原文作者: laozhao666

原文地址: http://my.eoe.cn/98783/archive/3345.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值