編輯:Android 資訊
本文將透過建立一個執行緒,在後台持續輪詢伺服器以獲取推送訊息,主要實現以下幾項功能:
@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 用來確保關閉所有執行緒。
/** * 獲取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推送信息的線程 */ 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通知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 上:
/** * 通過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 的大圖示顯示。
/** * 更新檢測對話框 * @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 中,此處不具體展示。
主要代碼到此基本結束。整體而言感覺還比較粗糙、耦合度較高,後續還有進一步封裝的空間,例如設置介面,將一些設定或處理邏輯暴露給外部調用等。這方面我目前也在學習中,若有更好的建議,歡迎一起探討!
深入解讀 Android 動畫 Interpolator 的運作原理
做過 Android 動畫的人對 Interpolator 應該不陌生。它的職責是控制動畫的執行速率。默認情況下,動畫並不是等速的——系統給的默認節奏是先加速再減速。 還
優雅地用 Kotlin 開發 Android:Anko 實戰與對照 Java 的寫法
寫在前面 上一篇我們看過 Kotlin 的優勢與基本語法,這次直接進到實作:如何在 Android 專案裡把 Kotlin 用起來,並與傳統 Java 寫法並排對照,你會
輕量級 Android 快取框架 ASimpleCache
本文由碼農網 – 小峰原創,轉載請看清文末的轉載要求,歡迎參與我們的付費投稿計劃! ASimpleCache 是一款基於 Android 的輕量級快取框架,全框架只有一個
深入 Android Activity 啟動流程:從 main() 一路追到 View 繪製
本文透過 DDMS 對一個簡單 Demo 做除錯標記,暫停主執行緒後觀察呼叫堆疊,逐層拆解 Activity 從被啟動到畫面真正呈現的完整路徑。一、起點:Activity