Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

Android 後台執行緒輪詢伺服器推送訊息的實作方案

編輯:Android 資訊

簡介

本文將透過建立一個執行緒,在後台持續輪詢伺服器以獲取推送訊息,主要實現以下幾項功能:

  • 建立執行緒類,做到可直接呼叫,於後台自動輪詢伺服器訊息,並對取得的訊息進行處理。
  • 獲取廣告等推廣資訊,透過 notification 通知使用者,點擊後跳轉到相關網頁。
  • 獲取 App 推送訊息,彈出更新對話方塊,提示符合條件的使用者進行升級、下載並安裝。

實現原理

  • Handler.postDelayed 用於以固定時間間隔去獲取伺服器訊息。
  • Notification 用於顯示推廣資訊,同時將接收到的圖片 url 轉化為 bitmap 並顯示其上。
  • AlertDialog 用於 App 更新提示,點擊即可升級。
  • annotation 中的 @SharedPref 方法用於儲存訊息 ID 號與訊息提示間隔,只有在時間間隔到來後才彈出訊息。

核心代碼

後台執行緒類

@EBean public class PushThread extends Thread { private Handler advertisementHandler; private Handler appPushHandler; private Context mContext; private int period = 2000; private NotificationManager mNM; private Notification notification; private boolean run; @Pref MyPrefs_ myPrefs; /** * 構造方法,初始化參數 * @param mContext */ public PushThread(Context mContext) { this.mContext = mContext; } /** * 啟動線程 */ public void startThread() { L.d("[PushThread] startThread"); run = true; advertisementHandler = new Handler(); appPushHandler = new Handler(); advertisementHandler.postDelayed(getAdvertisementRunable, period); L.d("PushThread run"); } /** * 停止線程 */ public void stopThread() { L.d("[PushThread] stopThread"); run = false; advertisementHandler.removeCallbacks(getAdvertisementRunable); appPushHandler.removeCallbacks(getAppPushRunable); } }

startThread() 負責初始化 Handler 並啟動執行緒;stopThread() 負責移除執行緒,標誌位 run 用來確保關閉所有執行緒。

Handler 實現輪詢獲取訊息

獲取推廣資訊

 /** * 獲取advertisement的線程 */ Runnable getAdvertisementRunable = new Runnable() { @Override public void run() { L.d("getAdvertisementRunable"); IotClass.getAdvertisementInfo("advertisement", new IotClass.OnPushInfoListener() { @Override public void receive(String respons) { Gson gson = new Gson(); AdvertismentBean advertismentBean = gson.fromJson(respons, AdvertismentBean.class); L.d("respons advertismentBean: " + advertismentBean); // L.d("respons: " + respons); if (myPrefs.advertisementId().get() == advertismentBean.getMessageId()) { if (myPrefs.advertisementFrequency().get() <= (System.currentTimeMillis() / 1000)) { L.d("[PushThread] getAdvertisementRunable time to show"); showNotification(advertismentBean); } else { L.d("[PushThread] getAdvertisementRunable wait..."); } } else { L.d("[PushThread] getAdvertisementRunable first show"); showNotification(advertismentBean); } } }); if (run) appPushHandler.postDelayed(getAppPushRunable, period); } };

IotClass 是自己寫好的一個網路請求類,IotClass.getAdvertisementInfo 方法負責獲取推送訊息,結果回呼後進行處理,並透過 Gson 序列化成物件:

Gson gson = new Gson(); AdvertismentBean advertismentBean = gson.fromJson(respons, AdvertismentBean.class);

後面是判斷 messageId:若是第一次獲取到 messageId 則顯示訊息,否則要等到時間間隔過了之後再顯示,最後透過 appPushHandler.postDelayed(getAppPushRunable, period) 繼續去輪詢 App 更新推送。

獲取 App 更新推送

/** * 獲取app推送信息的線程 */ Runnable getAppPushRunable = new Runnable() { @Override public void run() { IotClass.getAdvertisementInfo("android", new IotClass.OnPushInfoListener() { @Override public void receive(String respons) { String description; Gson gson = new Gson(); AppBean appBean = gson.fromJson(respons, AppBean.class); L.d("respons appBean: " + appBean); // L.d("respons: " + respons); if (myPrefs.appPushId().get() == appBean.getMessageId()){ if (myPrefs.appPushFrequency().get() <= (System.currentTimeMillis()/1000)) { description = getAppDescription(appBean); showUpgradeDialog(appBean, Utils.appDowanloadUrl+appBean.getAndroid_filename(), description); L.d("[PushThread] getAppPushRunable time to show"); } else{ L.d("[PushThread] getAppPushRunable wait..."); } }else{ description = getAppDescription(appBean); showUpgradeDialog(appBean, Utils.appDowanloadUrl+appBean.getAndroid_filename(), description); L.d("[PushThread] getAppPushRunable first show"); } } }); if (run) advertisementHandler.postDelayed(getAdvertisementRunable, period); } };

同理,獲取 App 更新推送的處理方式與獲取推廣資訊類似,最後透過 advertisementHandler.postDelayed(getAdvertisementRunable, period) 重新去獲取推廣資訊的推送,兩者相互呼叫,達到後台執行緒持續輪詢推送訊息的效果。其中 getAppDescription 用來判斷系統語言,以選擇更新提示中使用英文還是中文描述:

/** * 判斷系統語言版本,返回相應的更新說明 * @param appBean * @return */ private String getAppDescription(AppBean appBean) { if (Tools.isZh(mContext)) { return appBean.getDescription(); }else { return appBean.getDescription_en(); } }

下面是 AppBean 的類:

public class AppBean { String result; int messageId; long frequency; int android_build; String versionCode; String description; String description_en; String android_filename; String android_file_size; String android_id; @Override public String toString() { return "AppBean [result=" + result + ", messageId=" + messageId + ", frequency=" + frequency + ", android_build=" + android_build + ", versionCode=" + versionCode + ", description=" + description + ", description_en=" + description_en + ", android_filename=" + android_filename + ", android_file_size=" + android_file_size + ", android_id=" + android_id + "]"; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public int getMessageId() { return messageId; } public void setMessageId(int messageId) { this.messageId = messageId; } public long getFrequency() { return frequency; } public void setFrequency(long frequency) { this.frequency = frequency; } public int getAndroid_build() { return android_build; } public void setAndroid_build(int android_build) { this.android_build = android_build; } public String getVersionCode() { return versionCode; } public void setVersionCode(String versionCode) { this.versionCode = versionCode; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getDescription_en() { return description_en; } public void setDescription_en(String description_en) { this.description_en = description_en; } public String getAndroid_filename() { return android_filename; } public void setAndroid_filename(String android_filename) { this.android_filename = android_filename; } public String getAndroid_file_size() { return android_file_size; } public void setAndroid_file_size(String android_file_size) { this.android_file_size = android_file_size; } public String getAndroid_id() { return android_id; } public void setAndroid_id(String android_id) { this.android_id = android_id; } }

AdvertismentBean 與此類似,就不佔篇幅了。

推送訊息顯示等處理

Notification 顯示推廣資訊

Notification 常規訊息設定
/** * notification通知advertisement * @param advertismentBean */ private void showNotification(AdvertismentBean advertismentBean) { myPrefs.advertisementId().put(advertismentBean.getMessageId()); myPrefs.advertisementFrequency().put((int) (System.currentTimeMillis()/1000 + advertismentBean.getFrequency())); // The PendingIntent to launch our activity if the user selects this notification String url = advertismentBean.getUrl(); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0); //get largeIcon from url Bitmap largeIcon = getBitmap(advertismentBean.getLargeIcon()); // Set the info for the views that show in the notification panel. notification = new Notification.Builder(mContext) .setSmallIcon(R.drawable.logo) .setLargeIcon(largeIcon) .setWhen(System.currentTimeMillis()) .setTicker(advertismentBean.getContentTitle()) .setContentTitle(advertismentBean.getContentTitle()) .setContentText(advertismentBean.getContentText()) .setSubText(advertismentBean.getSubText()) .setContentIntent(contentIntent) .build(); // Send the notification. mNM.notify(advertismentBean.getMessageId(), notification); }

首先是儲存 ID 號與時間間隔,以便下次輪詢判斷使用;後面設定點擊事件,跳轉到相應的網頁頁面:

 String url = advertismentBean.getUrl(); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);

其餘則是常規的 notification 訊息內容設定。另外,下面用於獲取推送訊息中的圖片 url 並顯示於 notification 上:

Notification 獲取網路圖片作為圖示顯示
 /** * 通過URL獲取圖片,生成bitmap * @param path * @return */ public static Bitmap getBitmap(String path) { try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if (conn.getResponseCode() == 200) { InputStream inputStream = conn.getInputStream(); Bitmap bitmap = BitmapFactory.decodeStream(inputStream); return bitmap; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }

該方法實現了透過 url 轉化為 bitmap,用於 notification 的大圖示顯示。

AlertDialog 提示更新推送

 /** * 更新檢測對話框 * @param downloadUrl * @param newVersionInfo */ @UiThread void showUpgradeDialog(AppBean appBean, final String downloadUrl, String newVersionInfo) { myPrefs.appPushId().put(appBean.getMessageId()); myPrefs.appPushFrequency().put((int) (System.currentTimeMillis()/1000 + appBean.getFrequency())); final AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setTitle(R.string.Found_new_version).setMessage(newVersionInfo); builder.setPositiveButton(R.string.upgrade, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { IotClass.downLoadAppOrBin(mContext, downloadUrl, new ProgressDialog(mContext), IotClass.TYPE_APP); } }).setNegativeButton(R.string.show_next_time, null).show(); }

與訊息推送類似,點擊升級按鈕後下載並安裝,下載與安裝的動作封裝在 IotClass.downLoadAppOrBin 中,此處不具體展示。

總結

主要代碼到此基本結束。整體而言感覺還比較粗糙、耦合度較高,後續還有進一步封裝的空間,例如設置介面,將一些設定或處理邏輯暴露給外部調用等。這方面我目前也在學習中,若有更好的建議,歡迎一起探討!

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