android用鬧鐘定時做http請求推送的解決方案
設計思路
如果在開發(fā)當中需要做push接入,而產品又要求不允許用第三方sdk(百度push,友盟push),而且又沒有網絡編程的經驗,這個時候怎么辦?這里就給大家分享下用http請求解決這個問題。
大體的設計思路是,寫一個service(為了保證長時間運行不被kill,就將其定義到另外的進程當中去),在這個service里面啟動鬧鐘,每隔一段時間(這個時間可以自己定義)去請求服務器,如果有新的push消息,就通知給用戶。
具體實現(xiàn)
貌似很簡單定義一個鬧鐘不斷輪循請求服務器一句話,卻在實際開發(fā)中要考慮很多問題,下面簡單給大家列出來。
1)鬧鐘時間校準
2)每天push只能在固定的或者某個定義的時間內推送
3)push類型的擴展,新添加一種類型的push
什么都不說,類圖直接貼上
大概分為三級結構
第一級:MoboPushAlarmManager,主要工作是管理鬧鐘,初始化鬧鐘,對鬧鐘時間進行校準,取消鬧鐘。
第二級:MobogeniePushServiceNew,主要工作是對鬧鐘設置的pendingintent的動作(startservice)進行處理。
第三級:MoboPushNotifyHelper,主要工作是實例化notification對象,發(fā)送出通知,并且取消通知。MoboMessageSelector,主要工作是從n多個push中根據時間選擇出可用的push。MoboPushRequest,主要是請求服務器,從服務器列表中獲取push隊列。
其余的PushActionCreator,MoboPushMessage等等都屬于第三級或者第一第二級的工具類了。
開始來貼代碼了(具體的源碼還沒抽出來,過段時間再貼上)
MoboPushAlarmManager來初始化鬧鐘,當鬧鐘響了就會發(fā)送一個intent給MobogeniePushServiceNew
public void initPullAlarm(Context context, boolean boot) { Bundle bundle = new Bundle(); bundle.putInt(START_SERVICE_TYPE, TYPE_REQUEST); PendingIntent pendingIntent = getPendingIntent(context, bundle, REQ_PULL); //循環(huán)時間 long repeat_time = HOUR_MILLIS * 2; Log.i(TAG, "repeat_time is " + repeat_time); // 計算下一次執(zhí)行時間 long triggerAtMillis = boot ? 10000 : 0; Log.i(TAG, "initPullAlarm,and next pull time is after: " + triggerAtMillis); // 這個行為會覆蓋之前的Alarm,主要根據PendingIntent來辨別不同的鬧鐘 getAlarmManager(context).setRepeating(AlarmManager.RTC, System.currentTimeMillis() + triggerAtMillis, repeat_time, pendingIntent); }
MobogeniePushServiceNew接收到鬧鐘之后,就會解析intent,并且進行相應的操作(請求網絡,發(fā)送通知)
@Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); LogUtil.p("pushservice onStart"); if (intent == null) { LogUtil.d("mobopush", "intent == null)"); return; } // 解析打開service的意圖 parsePushServiceIntent(intent); } private void parsePushServiceIntent(Intent intent) { Log.i(TAG, "parsePushServiceIntent"); if (intent == null) { return; } Bundle bundle = intent.getExtras(); if (bundle == null) { // 不明渠道調起service,默認處理為準備獲取新消息,重設鬧鐘 PushAlarmManager.getInstance().initPullAlarm(this, false); return; } int type = bundle.getInt(PushAlarmManager.START_SERVICE_TYPE); if (type == PushAlarmManager.TYPE_STARTSERVICE) { //判斷鬧鐘是否過期,如果過期則重設 } else if (type == PushAlarmManager.TYPE_REQUEST) { // 預設的網絡請求 mREQ_RESULT = REQ_RESULT.ING; MoboPushRequest.getInstance().pullPushMessages(this, this, MoboPushRequest.REQUEST_NORMAL); } } //請求網絡回調的數據處理 @Override public void onMessageLoaded(int actionCode, int requestCode, MessageResponse response) { //將網絡請求回來的結果利用MessageSelector選擇器,選擇出有用的消息 getMessageSelector().assignMessageFromNet(MobogeniePushServiceNew.this, new MessageGetListener() { @Override public void showMessages(List<MoboPushMessage> msgs) { if (msgs.size() > 0) { for (MoboPushMessage msg : msgs) { notifyMessageAndDelete(msg, false); } } } @Override public void prepareMessages(List<MoboPushMessage> msgs) { if (msgs == null || msgs.size() == 0) { return; } MoboPushMessageDBUtils.insertBatch(MobogeniePushServiceNew.this, msgs); initShowMessageAlarm(msgs); } }, response.messages); }
MoboPushRequest去拉取新的消息
沒有寫網絡請求的部分,大家明白意思就行
public void pullPushMessages(Context context, final IMessageGetListener l, final int requestCode) { boolean pushFlag = true; if (!pushFlag) { return; } final Context appcontext = context.getApplicationContext(); //這里進行http請求,得到json數據 String json = ""; if (!TextUtils.isEmpty(json)) { JSONObject jsonObj = null; String str = null; try { jsonObj = new JSONObject(json); if (jsonObj.optInt("code") == 100) { int interval = jsonObj.optInt("interval"); MessageResponse response = new MessageResponse(); response.interval = interval * 1000; JSONArray jsonArray = jsonObj.optJSONArray("list"); if (jsonArray == null || jsonArray.length() == 0) { } int aLength = jsonArray.length(); response.initMessageArray(aLength); response.resCode = 100; for (int i = 0; i < aLength; i++) { JSONObject jsonInArray = jsonArray.getJSONObject(i); str = jsonInArray.toString(); MoboPushMessage pushMessage = new MoboPushMessage(); pushMessage.parseJson(str); response.messages[i] = pushMessage; if (pushMessage != null ) { } } } else { } } catch (JSONException e) { } } Object object=null; int actionCode=0; if (l == null) { return; } if (actionCode==0 && object != null && object instanceof MessageResponse) { MessageResponse response = (MessageResponse) object; l.onMessageLoaded(actionCode, requestCode, response); } else { l.onMessageLoaded(actionCode, requestCode, null); } }
剩下的就是處理具體的push消息了
private void notifyMessageAndDelete(MoboPushMessage message, boolean delete) { if (message == null) { return; } //傳入message對象發(fā)送通知 getMoboPushNotifyHelper().showNotification(message); }
我們只有message對象怎樣利用這個message對象去發(fā)送不同類型的push呢,為了很好的擴展,直接上代碼
public void showNotification(MoboPushMessage message) { final Intent targetIntent = obtainNotificationClick(message, false); setNotification(message, targetIntent); } public void setNotification(final MoboPushMessage message, final Intent intent) { //根據MoboPushMessage和Intent來show通知 }
重點就在這句話了,怎樣根據message檢測出需要的push呢
final Intent targetIntent = obtainNotificationClick(message, false);
我們可以看見getTargetIntent(mContext, message)這個方法主要作用
public Intent obtainNotificationClick(MoboPushMessage message, boolean flag) { if (message == null) { return null; } PushActionCreator actionCreator = new PushActionCreator(); return actionCreator.getTargetIntent(mContext, message); }
核心在這里
public Intent getTargetIntent(Context c,MoboPushMessage pushMessage){ if(pushMessage==null) { return null; } int type = pushMessage.type; Intent resultIntent = null; for(IPushIntentAction action:mPushActions){ if(action.isTypeForAction(type)){ try{ resultIntent = action.createTargetIntent(c,pushMessage); }catch(Exception e){ } break; } } return resultIntent; }
將不同類型的push對象添加到這個集合里面去
ArrayList<IPushIntentAction> mPushActions;
也就是所有的push數據都要實現(xiàn)這個公共的接口
public interface IPushIntentAction { public Intent createTargetIntent(Context context,MoboPushMessage message); public int getActionKey(); public boolean isTypeForAction(int type); public String getNextPage(); }
其中createTargetIntent這個根據不同的類型new出各自的intent,isTypeForAction比對類型
舉個例子大家就知道了。
public class PushActionDefault implements IPushIntentAction { @Override public Intent createTargetIntent(Context c, MoboPushMessage message) { Intent intent = new Intent(); intent.setAction("android.intent.action.MAIN"); intent.addCategory("android.intent.category.LAUNCHER"); return intent; } @Override public int getActionKey() { return MoboPushMessage.TYPE_OPEN_APP; } @Override public String getNextPage() { return null; } @Override public boolean isTypeForAction(int type) { return false; } }
基本上把一條線給貫穿了,其中
1)鬧鐘時間校準
解決方法可以自由的寫在初始化鬧鐘里面,如果發(fā)現(xiàn)時間有錯誤,可以再初始化一下鬧鐘,這樣就可以覆蓋以前的鬧鐘
2)每天push只能在固定的或者某個定義的時間內推送
我們在MoboMessageSelector選擇器里面專門對時間進行了篩選
3)push類型的擴展,新添加一種類型的push
我們要添加新的類型的push的時候,只需要實現(xiàn)IPushIntentAction 這個接口,然后在將對象添加到ArrayList mPushActions這個集合里面,供選擇就OK了
最近比較忙,之后一定把整理好的demo分享給大家。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- android實現(xiàn)定時拍照并發(fā)送微博功能
- android實現(xiàn)定時拍照功能
- Android使用自定義view在指定時間內勻速畫一條直線的實例代碼
- Android使用Handler實現(xiàn)定時器與倒計時器功能
- Android定時器和倒計時實現(xiàn)淘寶秒殺功能
- Android CountDownTimer實現(xiàn)定時器和倒計時效果
- android service實現(xiàn)循環(huán)定時提醒功能
- Android鬧鐘機制實現(xiàn)定時任務功能
- Android編程實現(xiàn)popupwindow定時消失的方法
- Android中AlarmManager+Notification實現(xiàn)定時通知提醒功能
- 詳解Android實現(xiàn)定時器的幾種方法
- Android定時開機的流程詳解
相關文章
Android最新版本開發(fā)環(huán)境搭建圖文教程
這篇文章主要為大家詳細介紹了Android最新版本開發(fā)環(huán)境搭建圖文教程,重點在于配置JDK,以及adt-bundle,感興趣的小伙伴們可以參考一下2016-07-07