From 2058294f425c5bcaf5eb61a7e7d7a4b1a957c8ae Mon Sep 17 00:00:00 2001 From: liyun Date: Mon, 17 Jun 2013 18:03:53 +0800 Subject: [PATCH 1/4] add gzip support for upload both Android SDK & PHP web --- .../com/wbtech/ums/common/NetworkUitlity.java | 33 ++++++++++++++++++- web/application/controllers/ums.php | 5 +++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/sdk/android_sdk/SDK/src/com/wbtech/ums/common/NetworkUitlity.java b/sdk/android_sdk/SDK/src/com/wbtech/ums/common/NetworkUitlity.java index f1e1762c..a8b771ce 100644 --- a/sdk/android_sdk/SDK/src/com/wbtech/ums/common/NetworkUitlity.java +++ b/sdk/android_sdk/SDK/src/com/wbtech/ums/common/NetworkUitlity.java @@ -13,9 +13,13 @@ */ package com.wbtech.ums.common; +import java.net.HttpURLConnection; +import java.net.URL; import java.net.URLDecoder; +import java.util.zip.GZIPOutputStream; import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; @@ -78,7 +82,34 @@ public static MyMessage post(String url, String data) { return message; } - + /** + * compress string use gzip to reduce the size + * */ + public static MyMessage postCompressed(String requestUrl,String data){ + MyMessage message = new MyMessage(); + try { + URL url = new URL(requestUrl); + HttpURLConnection conn = (HttpURLConnection)url.openConnection(); + conn.setDoOutput(true); + conn.setRequestProperty("Content-encoding", "gzip"); + conn.setRequestProperty("Content-type", "application/octet-stream"); + GZIPOutputStream dos1 = new GZIPOutputStream(conn.getOutputStream()); + dos1.write(data.getBytes("utf-8")); + dos1.flush(); + dos1.close(); + if(conn.getResponseCode() == HttpStatus.SC_OK){ + message.setFlag(true); + } else { + message.setFlag(false); + message.setMsg(conn.getResponseMessage()); + } + } catch (Exception e) { + Log.e("dakele", e.getMessage(), e); + } + message.setFlag(false); + return message; + } + diff --git a/web/application/controllers/ums.php b/web/application/controllers/ums.php index 70dd6bfe..db250285 100644 --- a/web/application/controllers/ums.php +++ b/web/application/controllers/ums.php @@ -283,6 +283,11 @@ function uploadLog() { return; } $encoded_content = $_POST ['content']; + if ( !isset( $HTTP_RAW_POST_DATA ) ) $HTTP_RAW_POST_DATA =file_get_contents( 'php://input' ); + if (isset($_SERVER['HTTP_CONTENT_TYPE']) && $_SERVER['HTTP_CONTENT_TYPE']=='gzip'){ + $encoded_content = gzinflate( substr($HTTP_RAW_POST_DATA,10,-8) ); + } + log_message ( "debug", $encoded_content ); $content = json_decode ( $encoded_content ); $key = $content->appkey; From 649271d9df90765f11f4caa6232f5723268dbb3e Mon Sep 17 00:00:00 2001 From: liyun Date: Mon, 17 Jun 2013 18:06:29 +0800 Subject: [PATCH 2/4] add gzip support for upload both Android SDK & PHP web --- sdk/android_sdk/SDK/src/com/wbtech/ums/UmsAgent.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/sdk/android_sdk/SDK/src/com/wbtech/ums/UmsAgent.java b/sdk/android_sdk/SDK/src/com/wbtech/ums/UmsAgent.java index 98074daf..f6fea631 100644 --- a/sdk/android_sdk/SDK/src/com/wbtech/ums/UmsAgent.java +++ b/sdk/android_sdk/SDK/src/com/wbtech/ums/UmsAgent.java @@ -19,7 +19,6 @@ import java.util.Iterator; import java.util.Locale; -import org.apache.http.util.LangUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -694,7 +693,7 @@ private static void uploadAllLog(Context context){ sb.append(new String(s,0,i)); } if(CommonUtil.isNetworkAvailable(context)){ - MyMessage message= NetworkUitlity.post(UmsConstants.preUrl+UmsConstants.uploadUrl, sb+""); + MyMessage message= NetworkUitlity.postCompressed(UmsConstants.preUrl+UmsConstants.uploadUrl, sb+""); if(message.isFlag()){ File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/mobclick_agent_cached_"+context.getPackageName()); file.delete(); From c29842effa67b5e0671087109995812f71eee9e8 Mon Sep 17 00:00:00 2001 From: liyun Date: Fri, 19 Jul 2013 13:57:29 +0800 Subject: [PATCH 3/4] update --- .../SDK/src/com/wbtech/ums/UmsAgent.java | 1470 ++++++++--------- .../com/wbtech/ums/common/NetworkUitlity.java | 97 +- .../ums/controller/EventController.java | 4 +- 3 files changed, 777 insertions(+), 794 deletions(-) diff --git a/sdk/android_sdk/SDK/src/com/wbtech/ums/UmsAgent.java b/sdk/android_sdk/SDK/src/com/wbtech/ums/UmsAgent.java index d2ff5113..f6dc12e9 100644 --- a/sdk/android_sdk/SDK/src/com/wbtech/ums/UmsAgent.java +++ b/sdk/android_sdk/SDK/src/com/wbtech/ums/UmsAgent.java @@ -39,771 +39,733 @@ import android.view.WindowManager; import android.widget.Toast; +import com.wbtech.ums.common.AssembJSONObj; import com.wbtech.ums.common.CommonUtil; import com.wbtech.ums.common.MD5Utility; import com.wbtech.ums.common.MyCrashHandler; import com.wbtech.ums.common.NetworkUitlity; import com.wbtech.ums.common.UmsConstants; +import com.wbtech.ums.controller.EventController; import com.wbtech.ums.dao.GetInfoFromFile; import com.wbtech.ums.dao.SaveInfo; import com.wbtech.ums.objects.LatitudeAndLongitude; import com.wbtech.ums.objects.MyMessage; +import com.wbtech.ums.objects.PostObjEvent; import com.wbtech.ums.objects.SCell; public class UmsAgent { - private static boolean mUseLocationService = true; - private static String start_millis = null;// The start time point - private static long start = 0; - private static String end_millis = null;// The end time point - private static long end = 0;// - private static String duration = null;// run time - private static String session_id = null; - private static String activities = null;// currnet activity's name - private static String appkey = ""; - private static String stacktrace = null;// error info - private static String time = null; // error time - private static String os_version = null; - private static String deviceID = null; - - private static String curVersion = null;// app version - private static String packagename = null;// app packagename - private static String sdk_version = null;// Sdk version - - private static UmsAgent umsAgentEntity = new UmsAgent(); - private static boolean mUpdateOnlyWifi = true; - private static int defaultReportMode = 0;// 0 send at next time,defaultmode - // 1 send at now - private static Handler handler; - private static boolean isPostFile = true; - private static boolean isFirst = true; - - // private static long tcp_sndofbegin=0; - // private static long tcp_rcvofbegin=0; - // private static long tcp_snd=0; - // private static long tcp_rcv=0; - - /** - * set base URL like http://81.30.76.26/pluggy/ums/index.php? - * - * @param url - */ - public static void setBaseURL(String url) { - UmsConstants.preUrl = url; - } - - public static void setSessionContinueMillis(long interval) { - if (interval > 0) { - UmsConstants.kContinueSessionMillis = interval; - } - - } - - public static void setAutoLocation(boolean AutoLocation) { - UmsAgent.mUseLocationService = AutoLocation; - } - - private UmsAgent() { - HandlerThread localHandlerThread = new HandlerThread("UmsAgent"); - localHandlerThread.start(); - this.handler = new Handler(localHandlerThread.getLooper()); - } - - public static UmsAgent getUmsAgent() { - return umsAgentEntity; - } - - public static void onError(final Context context) { - MyCrashHandler handler = MyCrashHandler.getInstance(); - handler.init(context.getApplicationContext()); - Thread.setDefaultUncaughtExceptionHandler(handler); - } - - public static void onError(final Context context, final String error) { - Runnable postErrorInfoRunnable = new Runnable() { - - @Override - public void run() { - postErrorInfo(context, error); - } - }; - handler.post(postErrorInfoRunnable); - } - - private static void postErrorInfo(Context context, String error) { - - stacktrace = error; - activities = CommonUtil.getActivityName(context); - time = CommonUtil.getTime(); - appkey = CommonUtil.getAppKey(context); - os_version = CommonUtil.getOsVersion(context); - deviceID = CommonUtil.getDeviceID(context); - - JSONObject errorInfo = getErrorInfoJSONObj(); - - if (1 == CommonUtil.getReportPolicyMode(context) && CommonUtil.isNetworkAvailable(context)) { - - MyMessage message = NetworkUitlity.post(UmsConstants.preUrl + UmsConstants.errorUrl, errorInfo.toString()); - if (!message.isFlag()) { - saveInfoToFile("errorInfo", errorInfo, context); - CommonUtil.printLog("error", message.getMsg()); - - } - } else { - saveInfoToFile("errorInfo", errorInfo, context); - } - } - - private static JSONObject getErrorInfoJSONObj() { - JSONObject errorInfo = new JSONObject(); - try { - Build bd = new Build(); - errorInfo.put("stacktrace", stacktrace); - errorInfo.put("time", time); - errorInfo.put("activity", activities); - errorInfo.put("appkey", appkey); - errorInfo.put("os_version", os_version); - errorInfo.put("deviceid", bd.MANUFACTURER + bd.PRODUCT); - } catch (JSONException e) { - e.printStackTrace(); - } - return errorInfo; - } - - /** - * Information is saved to a file by type - * - * @param type - * errorInfo/activityInfo/eventInfo/clinetDataInfo - * @param info - * @param context - */ - public static void saveInfoToFile(String type, JSONObject info, Context context) { - JSONArray newdata = new JSONArray(); - try { - newdata.put(0, info); - if (handler != null) { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(type, newdata); - handler.post(new SaveInfo(context, jsonObject)); - } else { - CommonUtil.printLog(CommonUtil.getActivityName(context), "handler--null"); - - } - } catch (JSONException e) { - e.printStackTrace(); - } - } - - public static void onEvent(final Context context, final String event_id) { - Runnable postEventInfo = new Runnable() { - public void run() { - postEventInfo(context, event_id); - } - }; - handler.post(postEventInfo); - } - - public static void onEvent(final Context context, final String event_id, final String label) { - Runnable postEventRunnable = new Runnable() { - - @Override - public void run() { - postEventInfo(context, event_id, label); - } - }; - handler.post(postEventRunnable); - } - - /** - * - * @param context - * @param event_id - */ - private static void postEventInfo(Context context, String event_id) { - onEvent(context, event_id, 1); - } - - private static void onEvent(Context context, String event_id, int acc) { - postEventInfo(context, event_id, null, acc); - } - - private static void postEventInfo(Context context, String event_id, String label) { - if ((label == null) || (label == "")) { - CommonUtil.printLog("UMSAgent", "label is null or empty in onEvent(4p)"); - return; - } - postEventInfo(context, event_id, label, 1); - } - - private static void postEventInfo(Context context, String event_id, String label, int acc) { - try { - String appkey = CommonUtil.getAppKey(context); - if (acc <= 0) { - CommonUtil.printLog("UMSAgent", "Illegal value of acc in postEventInfo"); - return; - } - new EventThread(context, appkey, event_id, label, acc).start(); - } catch (Exception e) { - CommonUtil.printLog("UMSAgent", "Exception occurred in postEventInfo()"); - e.printStackTrace(); - } - } - - /** - * Save the event time - */ - @SuppressWarnings("unused") - public static void saveEvent(UmsAgent umsAgent, Context context, String appkey, String event_id, String label, - int acc) { - umsAgentEntity = umsAgent; - umsAgentEntity.saveEvent(context, appkey, event_id, label, acc); - } - - private void saveEvent(Context context, String appkey, String event_id, String label, int acc) { - - JSONObject localJSONObject = getEventJOSNobj(context, label, event_id, acc); - - if (1 == CommonUtil.getReportPolicyMode(context) && CommonUtil.isNetworkAvailable(context)) { - try { - String eventUrl = UmsConstants.preUrl + UmsConstants.eventUrl; - CommonUtil.printLog("UMSAgent", "call post method. " + eventUrl); - MyMessage info = NetworkUitlity.post(eventUrl, localJSONObject.toString()); - CommonUtil.printLog("UmsAgent", info.getMsg().toString()); - if (!info.isFlag()) { - saveInfoToFile("eventInfo", localJSONObject, context); - CommonUtil.printLog("error", info.getMsg()); - } - CommonUtil.printLog("UmsAgent", "errorInfo" + info.getMsg()); - } catch (Exception e) { - CommonUtil.printLog("UmsAgent", "fail to post eventContent"); - } - } else { - - saveInfoToFile("eventInfo", localJSONObject, context); - } - } - - private JSONObject getEventJOSNobj(Context context, String label, String event_id, int acc) { - JSONObject localJSONObject = new JSONObject(); - String time = CommonUtil.getTime(); - appkey = CommonUtil.getAppKey(context); - try { - - localJSONObject.put("time", time); - localJSONObject.put("version", CommonUtil.getVersion(context)); - localJSONObject.put("event_identifier", event_id); - localJSONObject.put("appkey", appkey); - localJSONObject.put("activity", CommonUtil.getActivityName(context)); - if (label != null) - localJSONObject.put("label", label); - localJSONObject.put("acc", acc); - - } catch (JSONException localJSONException) { - CommonUtil.printLog("UmsAgent", "json error in emitCustomLogReport"); - localJSONException.printStackTrace(); - } - return localJSONObject; - } - - public static void onPause(final Context context) { - Runnable postOnPauseinfoRunnable = new Runnable() { - - @Override - public void run() { - postOnPauseInfo(context); - } - }; - handler.post(postOnPauseinfoRunnable); - } - - /** - * - * @param context - */ - private static void postOnPauseInfo(Context context) { - - saveSessionTime(context); - - end_millis = CommonUtil.getTime(); - end = Long.valueOf(System.currentTimeMillis()); - duration = end - start + ""; - appkey = CommonUtil.getAppKey(context); - JSONObject info = getJSONObject(context); - - CommonUtil.printLog("UmsAgent", info + ""); - - if (1 == CommonUtil.getReportPolicyMode(context) && CommonUtil.isNetworkAvailable(context)) { - CommonUtil.printLog("activityInfo", info.toString()); - - MyMessage message = NetworkUitlity.post(UmsConstants.preUrl + UmsConstants.activityUrl, info.toString()); - if (!message.isFlag()) { - saveInfoToFile("activityInfo", info, context); - CommonUtil.printLog("error", message.getMsg()); - - } - } else { - saveInfoToFile("activityInfo", info, context); - } - - } - - private static JSONObject getJSONObject(Context context) { - JSONObject info = new JSONObject(); - try { - info.put("session_id", session_id); - info.put("start_millis", start_millis); - info.put("end_millis", end_millis); - info.put("duration", duration); - info.put("version", CommonUtil.getVersion(context)); - info.put("activities", activities); - info.put("appkey", appkey); - } catch (JSONException e) { - e.printStackTrace(); - } - return info; - } - - public static void onResume(final Context context) { - Runnable postOnResumeinfoRunnable = new Runnable() { - - @Override - public void run() { - postonResume(context); - } - }; - handler.post(postOnResumeinfoRunnable); - } - - /** - * - * @param context - */ - private static void postonResume(Context context) { - if (!CommonUtil.isNetworkAvailable(context)) { - setDefaultReportPolicy(context, 0); - } else { - if (UmsAgent.isPostFile) { - Thread thread = new GetInfoFromFile(context); - thread.run(); - UmsAgent.isPostFile = false; - } - - } - - isCreateNewSessionID(context); - - activities = CommonUtil.getActivityName(context); - try { - if (session_id == null) { - generateSeesion(context); - } - - } catch (Exception e) { - e.printStackTrace(); - } - start_millis = CommonUtil.getTime(); - start = Long.valueOf(System.currentTimeMillis()); - - } - - private static void isCreateNewSessionID(Context context) { - // TODO Auto-generated method stub - long currenttime = System.currentTimeMillis(); - - SharedPreferences preferences = context.getSharedPreferences("UMS_session_ID_savetime", Context.MODE_PRIVATE); - long session_save_time = preferences.getLong("session_save_time", currenttime); - if (currenttime - session_save_time > UmsConstants.kContinueSessionMillis) { - try { - generateSeesion(context); - } catch (ParseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - } - - /** - * Automatic Updates - * - * @param context - */ - public static void update(final Context context) { - Runnable isupdateRunnable = new Runnable() { - - @Override - public void run() { - isupdate(context); - } - }; - handler.post(isupdateRunnable); - } - - private static void isupdate(Context context) { - try { - - appkey = CommonUtil.getAppKey(context); - - } catch (Exception e) { - String aString = end_millis.toString(); - Toast.makeText(context, aString, 1).show(); - - } - curVersion = CommonUtil.getCurVersion(context); - - JSONObject updateObject = new JSONObject(); - - try { - updateObject.put("appkey", appkey); - updateObject.put("version_code", curVersion); - } catch (JSONException e) { - e.printStackTrace(); - } - if (CommonUtil.isNetworkAvailable(context) && CommonUtil.isNetworkTypeWifi(context)) { - MyMessage message = NetworkUitlity.post(UmsConstants.preUrl + UmsConstants.updataUrl, - updateObject.toString()); - if (message.isFlag()) { - try { - JSONObject object = new JSONObject(message.getMsg()); - String flag = object.getString("flag"); - if (Integer.parseInt(flag) > 0) { - String fileurl = object.getString("fileurl"); - String msg = object.getString("msg"); - String forceupdate = object.getString("forceupdate"); - String description = object.getString("description"); - String time = object.getString("time"); - String version = object.getString("version"); - UpdateManager manager = new UpdateManager(context, version, forceupdate, fileurl, description); - manager.showNoticeDialog(context); - } - - } catch (JSONException e) { - e.printStackTrace(); - } - } else { - CommonUtil.printLog("error", message.getMsg()); - - } - } - } - - public static void updateOnlineConfig(final Context context) { - Runnable updateOnlineConfigRunnable = new Runnable() { - - @Override - public void run() { - updateOnlineConfigs(context); - } - }; - handler.post(updateOnlineConfigRunnable); - } - - /** - * get KEY-VALUE - * - * @param context - */ - private static void updateOnlineConfigs(Context context) { - appkey = CommonUtil.getAppKey(context); - JSONObject map = new JSONObject(); - try { - map.put("appkey", appkey); - } catch (JSONException e1) { - e1.printStackTrace(); - } - String appkeyJSON = map.toString(); - SharedPreferences preferences = context.getSharedPreferences( - "ums_agent_online_setting_" + CommonUtil.getPackageName(context), 0); - Editor editor = preferences.edit(); - - if (CommonUtil.isNetworkAvailable(context)) { - MyMessage message = NetworkUitlity.post(UmsConstants.preUrl + UmsConstants.onlineConfigUrl, appkeyJSON); - try { - CommonUtil.printLog("message", message.getMsg()); - if (message.isFlag()) { - JSONObject object = new JSONObject(message.getMsg()); - - if (UmsConstants.DebugMode) { - CommonUtil.printLog("uploadJSON", object.toString()); - } - - Iterator iterator = object.keys(); - - while (iterator.hasNext()) { - String key = iterator.next(); - String value = object.getString(key); - editor.putString(key, value); - if (key.equals("autogetlocation") && (!value.equals("1"))) { - setAutoLocation(false); - } - - if (key.equals("updateonlywifi") && (!value.equals("1"))) { - setUpdateOnlyWifi(false); - } - if (key.equals("reportpolicy") && (value.equals("1"))) { - setDefaultReportPolicy(context, 1); - } - if (key.equals("sessionmillis")) { - UmsConstants.kContinueSessionMillis = Integer.parseInt(value) * 1000; - } - } - editor.commit(); - - } else { - CommonUtil.printLog("error", message.getMsg()); - - } - } catch (JSONException e) { - e.printStackTrace(); - } - } else { - CommonUtil.printLog("UMSAgent", " updateOnlineConfig network error"); - - } - - } - - /** - * get online value by key - * - * @param context - * @param onlineKey - * @return - */ - public static String getConfigParams(Context context, String onlineKey) { - - appkey = CommonUtil.getAppKey(context); - JSONObject json = new JSONObject(); - try { - json.put("appkey", appkey); - } catch (JSONException e1) { - e1.printStackTrace(); - } - String appkeyJSON = json.toString(); - if (CommonUtil.isNetworkAvailable(context)) { - MyMessage message = NetworkUitlity.post(UmsConstants.preUrl + UmsConstants.onlineConfigUrl, appkeyJSON); - if (message.isFlag()) { - try { - JSONObject object = new JSONObject(message.getMsg()); - return object.getString(onlineKey); - - } catch (JSONException e) { - e.printStackTrace(); - } - } else { - CommonUtil.printLog("error", "getConfigParams error"); - } - } else { - CommonUtil.printLog("NetworkError", "Network, not work"); - } - return ""; - } - - /** - * - * @param isUpdateonlyWifi - */ - public static void setUpdateOnlyWifi(boolean isUpdateonlyWifi) { - UmsAgent.mUpdateOnlyWifi = isUpdateonlyWifi; - CommonUtil.printLog("mUpdateOnlyWifi value", UmsAgent.mUpdateOnlyWifi + ""); - } - - /** - * Setting data transmission mode - * - * @param context - * @param reportModel - */ - public static void setDefaultReportPolicy(Context context, int reportModel) { - CommonUtil.printLog("reportType", reportModel + ""); - if ((reportModel == 0) || (reportModel == 1)) { - - UmsAgent.defaultReportMode = reportModel; - String str = context.getPackageName(); - SharedPreferences localSharedPreferences = context.getSharedPreferences("ums_agent_online_setting_" + str, - 0); - synchronized (UmsConstants.saveOnlineConfigMutex) { - localSharedPreferences.edit().putInt("ums_local_report_policy", reportModel).commit(); - } - } - } - - /** - * - * create sessionID - * - * @param context - * @return sessionId - * @throws ParseException - */ - private static String generateSeesion(Context context) throws ParseException { - String sessionId = ""; - String str = CommonUtil.getAppKey(context); - if (str != null) { - String localDate = CommonUtil.getTime(); - str = str + localDate; - sessionId = MD5Utility.md5Appkey(str); - SharedPreferences preferences = context.getSharedPreferences("UMS_sessionID", Context.MODE_PRIVATE); - Editor edit = preferences.edit(); - edit.putString("session_id", sessionId); - edit.commit(); - saveSessionTime(context); - session_id = sessionId; - return sessionId; - } - return sessionId; - } - - private static void saveSessionTime(Context context) { - // TODO Auto-generated method stub - SharedPreferences preferences2sessiontime = context.getSharedPreferences("UMS_session_ID_savetime", - Context.MODE_PRIVATE); - Editor editor = preferences2sessiontime.edit(); - long currenttime = System.currentTimeMillis(); - editor.putLong("session_save_time", currenttime); - editor.commit(); - } - - /** - * Upload all data - * - * @param context - */ - public static void uploadLog(final Context context) { - Runnable uploadLogRunnable = new Runnable() { - - @Override - public void run() { - uploadAllLog(context); - } - }; - handler.post(uploadLogRunnable); - } - - private static void uploadAllLog(Context context) { - - File file1 = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/mobclick_agent_cached_" - + context.getPackageName()); - if (file1.exists()) { - try { - FileInputStream in = new FileInputStream(Environment.getExternalStorageDirectory().getAbsolutePath() - + "/mobclick_agent_cached_" + context.getPackageName()); - StringBuffer sb = new StringBuffer(); - - int i = 0; - byte[] s = new byte[1024 * 4]; - - while ((i = in.read(s)) != -1) { - - sb.append(new String(s, 0, i)); - } - if (CommonUtil.isNetworkAvailable(context)) { - MyMessage message = NetworkUitlity.postCompressed(UmsConstants.preUrl + UmsConstants.uploadUrl, sb - + ""); - if (message.isFlag()) { - File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() - + "/mobclick_agent_cached_" + context.getPackageName()); - file.delete(); - } else { - CommonUtil.printLog("uploadError", "uploadLog Error"); - } - } else { - CommonUtil.printLog("NetworkError", "Network, not work"); - } - - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - /** - * \ upload client device information - * - * @param context - */ - public static void postClientData(final Context context) { - Runnable postClientDataRunnable = new Runnable() { - - @Override - public void run() { - postClientDatas(context); - } - }; - handler.post(postClientDataRunnable); - - } - - private static void postClientDatas(Context context) { - if (isFirst) { - - JSONObject clientData = getClientDataJSONObject(context); - - if (1 == CommonUtil.getReportPolicyMode(context) & CommonUtil.isNetworkAvailable(context)) { - MyMessage message = NetworkUitlity.post(UmsConstants.preUrl + UmsConstants.clientDataUrl, - clientData.toString()); - if (!message.isFlag()) { - saveInfoToFile("clientData", clientData, context); - CommonUtil.printLog("Errorinfo", message.getMsg()); - } - } else { - saveInfoToFile("clientData", clientData, context); - } - isFirst = false; - - } - } - - private static JSONObject getClientDataJSONObject(Context context) { - TelephonyManager tm = (TelephonyManager) (context.getSystemService(Context.TELEPHONY_SERVICE)); - WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); - WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); - DisplayMetrics displaysMetrics = new DisplayMetrics(); - manager.getDefaultDisplay().getMetrics(displaysMetrics); - LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); - BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); - JSONObject clientData = new JSONObject(); - try { - clientData.put("os_version", CommonUtil.getOsVersion(context)); - clientData.put("platform", "android"); - clientData.put("language", Locale.getDefault().getLanguage()); - clientData.put("deviceid", tm.getDeviceId() == null ? "" : tm.getDeviceId());// - clientData.put("appkey", CommonUtil.getAppKey(context)); - clientData.put("resolution", displaysMetrics.widthPixels + "x" + displaysMetrics.heightPixels); - clientData.put("ismobiledevice", true); - clientData.put("phonetype", tm.getPhoneType());// - clientData.put("imsi", tm.getSubscriberId()); - clientData.put("network", CommonUtil.getNetworkType(context)); - clientData.put("time", CommonUtil.getTime()); - clientData.put("version", CommonUtil.getVersion(context)); - - SCell sCell = CommonUtil.getCellInfo(context); - - clientData.put("mccmnc", sCell != null ? "" + sCell.MCCMNC : ""); - clientData.put("cellid", sCell != null ? sCell.CID + "" : ""); - clientData.put("lac", sCell != null ? sCell.LAC + "" : ""); - - Build bd = new Build(); - - clientData.put("modulename", bd.MODEL); - clientData.put("devicename", bd.MANUFACTURER + bd.PRODUCT); - clientData.put("wifimac", wifiManager.getConnectionInfo().getMacAddress()); - clientData.put("havebt", adapter == null ? false : true); - clientData.put("havewifi", CommonUtil.isWiFiActive(context)); - clientData.put("havegps", locationManager == null ? false : true); - clientData.put("havegravity", CommonUtil.isHaveGravity(context));// - - LatitudeAndLongitude coordinates = CommonUtil - .getLatitudeAndLongitude(context, UmsAgent.mUseLocationService); - clientData.put("latitude", coordinates.latitude); - clientData.put("longitude", coordinates.longitude); - CommonUtil.printLog("clientData---------->", clientData.toString()); - } catch (JSONException e) { - e.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); - } - return clientData; - } + private static boolean mUseLocationService = true; + private static String start_millis = null;// The start time point + private static long start = 0; + private static String end_millis = null;// The end time point + private static long end = 0;// + private static String duration = null;// run time + private static String session_id = null; + private static String activities = null;// currnet activity's name + private static String appkey = ""; + private static String stacktrace = null;// error info + private static String time = null; // error time + private static String os_version = null; + private static String deviceID = null; + + private static String curVersion = null;// app version + private static String packagename = null;// app packagename + private static String sdk_version = null;// Sdk version + + private static UmsAgent umsAgentEntity = new UmsAgent(); + private static boolean mUpdateOnlyWifi = true; + private static int defaultReportMode = 0;// 0 send at next time's defaultmode + // 1 send at now + private static Handler handler; + private static boolean isPostFile = true; + private static boolean isFirst = true; + + private static String UserIdentifier = "userid"; + + // private static long tcp_sndofbegin=0; + // private static long tcp_rcvofbegin=0; + // private static long tcp_snd=0; + // private static long tcp_rcv=0; + + /** + * set base URL like http://81.30.76.26/pluggy/ums/index.php? + * + * @param url + */ + public static void setBaseURL(String url) { + UmsConstants.preUrl = url; + + } + + public static void setSessionContinueMillis(long interval) { + if (interval > 0) { + UmsConstants.kContinueSessionMillis = interval; + } + + } + + public static void setAutoLocation(boolean AutoLocation) { + UmsAgent.mUseLocationService = AutoLocation; + } + + private UmsAgent() { + HandlerThread localHandlerThread = new HandlerThread("UmsAgent"); + localHandlerThread.start(); + this.handler = new Handler(localHandlerThread.getLooper()); + } + + public static UmsAgent getUmsAgent() { + return umsAgentEntity; + } + + /** + * bind user + * + * @param identifier + */ + public static String bindUserIdentifier(final Context context, final String identifier) { + String packageName = context.getPackageName(); + SharedPreferences localSharedPreferences = context + .getSharedPreferences("ums_agent_online_setting_" + packageName, 0); + localSharedPreferences.edit().putString("identifier", identifier).commit(); + return localSharedPreferences.getString("identifier", ""); + } + + /** + * @param context + */ + public static void onError(final Context context) { + MyCrashHandler handler = MyCrashHandler.getInstance(); + handler.init(context.getApplicationContext()); + Thread.setDefaultUncaughtExceptionHandler(handler); + } + + /** + * post error info + * + * @param context + * @param error + */ + public static void onError(final Context context, final String error) { + Runnable postErrorInfoRunnable = new Runnable() { + + @Override + public void run() { + postErrorInfo(context, error); + } + }; + handler.post(postErrorInfoRunnable); + } + + private static void postErrorInfo(Context context, String error) { + + JSONObject errorInfo = AssembJSONObj.getErrorInfoJSONObj(error, context); + try { + errorInfo.put(UserIdentifier, CommonUtil.getUserIdentifier(context)); + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + if (1 == CommonUtil.getReportPolicyMode(context) && CommonUtil.isNetworkAvailable(context)) { + + MyMessage message = NetworkUitlity.post(UmsConstants.preUrl + UmsConstants.errorUrl, + errorInfo.toString()); + if (!message.isFlag()) { + saveInfoToFile("errorInfo", errorInfo, context); + CommonUtil.printLog("error", message.getMsg()); + + } + } else { + saveInfoToFile("errorInfo", errorInfo, context); + } + } + + /** + * Information is saved to a file by type + * + * @param type errorInfo/activityInfo/eventInfo/clinetDataInfo + * @param info + * @param context + */ + public static void saveInfoToFile(String type, JSONObject info, Context context) { + JSONArray newdata = new JSONArray(); + try { + newdata.put(0, info); + if (handler != null) { + JSONObject jsonObject = new JSONObject(); + jsonObject.put(type, newdata); + handler.post(new SaveInfo(context, jsonObject)); + } else { + CommonUtil.printLog(CommonUtil.getActivityName(context), "handler--null"); + + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + + public static void onEvent(final Context context, final String event_id) { + Runnable postEventInfo = new Runnable() { + public void run() { + onEvent(context, event_id, 1); + } + }; + handler.post(postEventInfo); + } + + public static void onEvent(final Context context, final String event_id, final String label, + final int acc) { + Runnable postEventRunnable = new Runnable() { + + @Override + public void run() { + EventController.postEventInfo(handler,context,new PostObjEvent( event_id, label, acc + "",context)); + } + }; + handler.post(postEventRunnable); + } + + + public static void onEvent(Context context, String event_id, int acc) { + if(handler==null){ + HandlerThread localHandlerThread = new HandlerThread("UmsAgent"); + localHandlerThread.start(); + handler = new Handler(localHandlerThread.getLooper()); + } + EventController.postEventInfo(handler,context, new PostObjEvent(event_id, null, acc + "",context)); + } + + public static void onPause(final Context context) { + Runnable postOnPauseinfoRunnable = new Runnable() { + + @Override + public void run() { + postOnPauseInfo(context); + } + }; + handler.post(postOnPauseinfoRunnable); + } + + /** + * @param context + */ + private static void postOnPauseInfo(Context context) { + + saveSessionTime(context); + + end_millis = CommonUtil.getTime(); + end = Long.valueOf(System.currentTimeMillis()); + duration = end - start + ""; + appkey = CommonUtil.getAppKey(context); + JSONObject info = getJSONObject(context); + + CommonUtil.printLog("UmsAgent", info + ""); + + if (1 == CommonUtil.getReportPolicyMode(context) && CommonUtil.isNetworkAvailable(context)) { + CommonUtil.printLog("activityInfo", info.toString()); + + MyMessage message = NetworkUitlity.post(UmsConstants.preUrl + UmsConstants.activityUrl, + info.toString()); + if (!message.isFlag()) { + saveInfoToFile("activityInfo", info, context); + CommonUtil.printLog("error", message.getMsg()); + + } + } else { + saveInfoToFile("activityInfo", info, context); + } + + } + + private static JSONObject getJSONObject(Context context) { + JSONObject info = new JSONObject(); + try { + info.put("session_id", session_id); + info.put("start_millis", start_millis); + info.put("end_millis", end_millis); + info.put("duration", duration); + info.put("version", CommonUtil.getVersion(context)); + info.put("activities", activities); + info.put("appkey", appkey); + // info.put(UserIdentifier, CommonUtil.getUserIdentifier(context)); + } catch (JSONException e) { + e.printStackTrace(); + } + return info; + } + + public static void onResume(final Context context) { + Runnable postOnResumeinfoRunnable = new Runnable() { + + @Override + public void run() { + postonResume(context); + } + }; + handler.post(postOnResumeinfoRunnable); + } + + /** + * @param context + */ + private static void postonResume(Context context) { + if (!CommonUtil.isNetworkAvailable(context)) { + setDefaultReportPolicy(context, 0); + } else { + if (UmsAgent.isPostFile) { + Thread thread = new GetInfoFromFile(context); + thread.run(); + UmsAgent.isPostFile = false; + } + + } + + isCreateNewSessionID(context); + + activities = CommonUtil.getActivityName(context); + try { + if (session_id == null) { + generateSeesion(context); + } + + } catch (Exception e) { + e.printStackTrace(); + } + start_millis = CommonUtil.getTime(); + start = Long.valueOf(System.currentTimeMillis()); + + } + + private static void isCreateNewSessionID(Context context) { + // TODO Auto-generated method stub + long currenttime = System.currentTimeMillis(); + + SharedPreferences preferences = context.getSharedPreferences("UMS_session_ID_savetime", + Context.MODE_PRIVATE); + long session_save_time = preferences.getLong("session_save_time", currenttime); + if (currenttime - session_save_time > UmsConstants.kContinueSessionMillis) { + try { + generateSeesion(context); + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + } + +// private static void isCreateNewSessionID(Context context) { +// // TODO Auto-generated method stub +// long currenttime = System.currentTimeMillis(); +// +// SharedPreferences preferences = context.getSharedPreferences("UMS_session_ID_savetime", +// Context.MODE_PRIVATE); +// long session_save_time = preferences.getLong("session_save_time", currenttime); +// if (currenttime - session_save_time > UmsConstants.kContinueSessionMillis) { +// try { +// generateSeesion(context); +// } catch (ParseException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } +// } +// +// } + + /** + * Automatic Updates + * + * @param context + */ + public static void update(final Context context) { + Runnable isupdateRunnable = new Runnable() { + + @Override + public void run() { + isupdate(context); + } + }; + handler.post(isupdateRunnable); + } + + private static void isupdate(Context context) { + try { + + appkey = CommonUtil.getAppKey(context); + + } catch (Exception e) { + String aString = end_millis.toString(); + Toast.makeText(context, aString, 1).show(); + + } + curVersion = CommonUtil.getCurVersion(context); + + JSONObject updateObject = new JSONObject(); + + try { + updateObject.put("appkey", appkey); + updateObject.put("version_code", curVersion); + } catch (JSONException e) { + e.printStackTrace(); + } + if (CommonUtil.isNetworkAvailable(context) && CommonUtil.isNetworkTypeWifi(context)) { + MyMessage message = NetworkUitlity.post(UmsConstants.preUrl + UmsConstants.updataUrl, + updateObject.toString()); + if (message.isFlag()) { + try { + JSONObject object = new JSONObject(message.getMsg()); + String flag = object.getString("flag"); + if (Integer.parseInt(flag) > 0) { + String fileurl = object.getString("fileurl"); + String msg = object.getString("msg"); + String forceupdate = object.getString("forceupdate"); + String description = object.getString("description"); + String time = object.getString("time"); + String version = object.getString("version"); + UpdateManager manager = new UpdateManager(context, version, forceupdate, + fileurl, description); + manager.showNoticeDialog(context); + } + + } catch (JSONException e) { + e.printStackTrace(); + } + } else { + CommonUtil.printLog("error", message.getMsg()); + + } + } + } + + public static void updateOnlineConfig(final Context context) { + Runnable updateOnlineConfigRunnable = new Runnable() { + + @Override + public void run() { + updateOnlineConfigs(context); + } + }; + handler.post(updateOnlineConfigRunnable); + } + + /** + * get KEY-VALUE + * + * @param context + */ + private static void updateOnlineConfigs(Context context) { + appkey = CommonUtil.getAppKey(context); + JSONObject map = new JSONObject(); + try { + map.put("appkey", appkey); + } catch (JSONException e1) { + e1.printStackTrace(); + } + String appkeyJSON = map.toString(); + SharedPreferences preferences = context.getSharedPreferences( + "ums_agent_online_setting_" + + CommonUtil.getPackageName(context), 0); + Editor editor = preferences.edit(); + + if (CommonUtil.isNetworkAvailable(context)) { + MyMessage message = NetworkUitlity + .post(UmsConstants.preUrl + UmsConstants.onlineConfigUrl, appkeyJSON); + try { + CommonUtil.printLog("message", message.getMsg()); + if (message.isFlag()) { + JSONObject object = new JSONObject(message.getMsg()); + + if (UmsConstants.DebugMode) { + CommonUtil.printLog("uploadJSON", object.toString()); + } + + Iterator iterator = object.keys(); + + while (iterator.hasNext()) { + String key = iterator.next(); + String value = object.getString(key); + editor.putString(key, value); + if (key.equals("autogetlocation") && (!value.equals("1"))) { + setAutoLocation(false); + } + + if (key.equals("updateonlywifi") && (!value.equals("1"))) { + setUpdateOnlyWifi(false); + } + if (key.equals("reportpolicy") && (value.equals("1"))) { + setDefaultReportPolicy(context, 1); + } + if (key.equals("sessionmillis")) { + UmsConstants.kContinueSessionMillis = Integer.parseInt(value) * 1000; + } + } + editor.commit(); + + } else { + CommonUtil.printLog("error", message.getMsg()); + + } + } catch (JSONException e) { + e.printStackTrace(); + } + } else { + CommonUtil.printLog("UMSAgent", " updateOnlineConfig network error"); + + } + + } + + /** + * get online value by key + * + * @param context + * @param onlineKey + * @return + */ + public static String getConfigParams(Context context, + String onlineKey) { + + appkey = CommonUtil.getAppKey(context); + JSONObject json = new JSONObject(); + try { + json.put("appkey", appkey); + } catch (JSONException e1) { + e1.printStackTrace(); + } + String appkeyJSON = json.toString(); + if (CommonUtil.isNetworkAvailable(context)) { + MyMessage message = NetworkUitlity + .post(UmsConstants.preUrl + UmsConstants.onlineConfigUrl, appkeyJSON); + if (message.isFlag()) { + try { + JSONObject object = new JSONObject(message.getMsg()); + return object.getString(onlineKey); + + } catch (JSONException e) { + e.printStackTrace(); + } + } else { + CommonUtil.printLog("error", "getConfigParams error"); + } + } else { + CommonUtil.printLog("NetworkError", "Network, not work"); + } + return ""; + } + + /** + * @param isUpdateonlyWifi + */ + public static void setUpdateOnlyWifi(boolean isUpdateonlyWifi) { + UmsAgent.mUpdateOnlyWifi = isUpdateonlyWifi; + CommonUtil.printLog("mUpdateOnlyWifi value", UmsAgent.mUpdateOnlyWifi + ""); + } + + /** + * Setting data transmission mode + * + * @param context + * @param reportModel + */ + public static void setDefaultReportPolicy(Context context, int reportModel) { + CommonUtil.printLog("reportType", reportModel + ""); + if ((reportModel == 0) || (reportModel == 1)) { + + UmsAgent.defaultReportMode = reportModel; + String packageName = context.getPackageName(); + SharedPreferences localSharedPreferences = context + .getSharedPreferences("ums_agent_online_setting_" + packageName, 0); + synchronized (UmsConstants.saveOnlineConfigMutex) { + localSharedPreferences.edit().putInt("ums_local_report_policy", + reportModel).commit(); + } + } + } + + /** + * create sessionID + * + * @param context + * @return sessionId + * @throws ParseException + */ + private static String generateSeesion(Context context) + throws ParseException { + String sessionId = ""; + String str = CommonUtil.getAppKey(context); + if (str != null) { + String localDate = CommonUtil.getTime(); + str = str + localDate; + sessionId = MD5Utility.md5Appkey(str); + SharedPreferences preferences = context.getSharedPreferences("UMS_sessionID", + Context.MODE_PRIVATE); + Editor edit = preferences.edit(); + edit.putString("session_id", sessionId); + edit.commit(); + saveSessionTime(context); + session_id = sessionId; + return sessionId; + } + return sessionId; + } + + private static void saveSessionTime(Context context) { + // TODO Auto-generated method stub + SharedPreferences preferences2sessiontime = context.getSharedPreferences( + "UMS_session_ID_savetime", Context.MODE_PRIVATE); + Editor editor = preferences2sessiontime.edit(); + long currenttime = System.currentTimeMillis(); + editor.putLong("session_save_time", currenttime); + editor.commit(); + } + + /** + * Upload all data + * + * @param context + */ + public static void uploadLog(final Context context) { + Runnable uploadLogRunnable = new Runnable() { + + @Override + public void run() { + uploadAllLog(context); + } + }; + handler.post(uploadLogRunnable); + } + + private static void uploadAllLog(Context context) { + + File file1 = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + + "/mobclick_agent_cached_" + context.getPackageName()); + if (file1.exists()) { + try { + FileInputStream in = new FileInputStream(Environment.getExternalStorageDirectory() + .getAbsolutePath() + "/mobclick_agent_cached_" + context.getPackageName()); + StringBuffer sb = new StringBuffer(); + + int i = 0; + byte[] s = new byte[1024 * 4]; + + while ((i = in.read(s)) != -1) { + + sb.append(new String(s, 0, i)); + } + if (CommonUtil.isNetworkAvailable(context)) { + MyMessage message = NetworkUitlity.postCompressed(UmsConstants.preUrl + + UmsConstants.uploadUrl, sb + ""); + if (message.isFlag()) { + File file = new File(Environment.getExternalStorageDirectory() + .getAbsolutePath() + + "/mobclick_agent_cached_" + + context.getPackageName()); + file.delete(); + } else { + CommonUtil.printLog("uploadError", "uploadLog Error"); + } + } else { + CommonUtil.printLog("NetworkError", "Network, not work"); + } + + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + /** + * \ upload client device information + * + * @param context + */ + public static void postClientData(final Context context) { + Runnable postClientDataRunnable = new Runnable() { + + @Override + public void run() { + postClientDatas(context); + } + }; + handler.post(postClientDataRunnable); + + } + + private static void postClientDatas(Context context) { + if (isFirst) { + + JSONObject clientData = getClientDataJSONObject(context); + + if (1 == CommonUtil.getReportPolicyMode(context) + & CommonUtil.isNetworkAvailable(context)) { + MyMessage message = NetworkUitlity.post(UmsConstants.preUrl + + UmsConstants.clientDataUrl, clientData.toString()); + if (!message.isFlag()) { + saveInfoToFile("clientData", clientData, context); + CommonUtil.printLog("Errorinfo", message.getMsg()); + } + } else { + saveInfoToFile("clientData", clientData, context); + } + isFirst = false; + + } + } + + private static JSONObject getClientDataJSONObject(Context context) { + TelephonyManager tm = (TelephonyManager) (context + .getSystemService(Context.TELEPHONY_SERVICE)); + WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); + WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); + DisplayMetrics displaysMetrics = new DisplayMetrics(); + manager.getDefaultDisplay().getMetrics(displaysMetrics); + LocationManager locationManager = (LocationManager) context + .getSystemService(Context.LOCATION_SERVICE); + BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); + JSONObject clientData = new JSONObject(); + try { + clientData.put("os_version", CommonUtil.getOsVersion(context)); + clientData.put("platform", "android"); + clientData.put("language", Locale.getDefault().getLanguage()); + clientData.put("deviceid", tm.getDeviceId() == null ? "" : tm.getDeviceId());// + clientData.put("appkey", CommonUtil.getAppKey(context)); + clientData.put("resolution", displaysMetrics.widthPixels + "x" + + displaysMetrics.heightPixels); + clientData.put("ismobiledevice", true); + clientData.put("phonetype", tm.getPhoneType());// + clientData.put("imsi", tm.getSubscriberId()); + clientData.put("network", CommonUtil.getNetworkType(context)); + clientData.put("time", CommonUtil.getTime()); + clientData.put("version", CommonUtil.getVersion(context)); + clientData.put(UserIdentifier, CommonUtil.getUserIdentifier(context)); + + SCell sCell = CommonUtil.getCellInfo(context); + + clientData.put("mccmnc", sCell != null ? "" + sCell.MCCMNC : ""); + clientData.put("cellid", sCell != null ? sCell.CID + "" : ""); + clientData.put("lac", sCell != null ? sCell.LAC + "" : ""); + + Build bd = new Build(); + + clientData.put("modulename", bd.MODEL); + clientData.put("devicename", bd.MANUFACTURER + bd.PRODUCT); + clientData.put("wifimac", wifiManager.getConnectionInfo().getMacAddress()); + clientData.put("havebt", adapter == null ? false : true); + clientData.put("havewifi", CommonUtil.isWiFiActive(context)); + clientData.put("havegps", locationManager == null ? false : true); + clientData.put("havegravity", CommonUtil.isHaveGravity(context));// + + LatitudeAndLongitude coordinates = CommonUtil.getLatitudeAndLongitude(context, + UmsAgent.mUseLocationService); + clientData.put("latitude", coordinates.latitude); + clientData.put("longitude", coordinates.longitude); + CommonUtil.printLog("clientData---------->", clientData.toString()); + } catch (JSONException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + return clientData; + } } diff --git a/sdk/android_sdk/SDK/src/com/wbtech/ums/common/NetworkUitlity.java b/sdk/android_sdk/SDK/src/com/wbtech/ums/common/NetworkUitlity.java index a8b771ce..2912fbc6 100644 --- a/sdk/android_sdk/SDK/src/com/wbtech/ums/common/NetworkUitlity.java +++ b/sdk/android_sdk/SDK/src/com/wbtech/ums/common/NetworkUitlity.java @@ -32,24 +32,26 @@ import android.util.Log; import com.wbtech.ums.objects.MyMessage; + public class NetworkUitlity { public static long paramleng = 256L; - public static String DEFAULT_CHARSET=" HTTP.UTF_8"; + public static String DEFAULT_CHARSET = " HTTP.UTF_8"; + public static MyMessage post(String url, String data) { // TODO Auto-generated method stub - CommonUtil.printLog("ums",url); + CommonUtil.printLog("ums", url); String returnContent = ""; - MyMessage message=new MyMessage(); + MyMessage message = new MyMessage(); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); try { - StringEntity se = new StringEntity("content="+data, HTTP.UTF_8); - CommonUtil.printLog("postdata", "content="+data); + StringEntity se = new StringEntity("content=" + data, HTTP.UTF_8); + CommonUtil.printLog("postdata", "content=" + data); se.setContentType("application/x-www-form-urlencoded"); httppost.setEntity(se); HttpResponse response = httpclient.execute(httppost); int status = response.getStatusLine().getStatusCode(); - CommonUtil.printLog("ums",status+""); + CommonUtil.printLog("ums", status + ""); String returnXML = EntityUtils.toString(response.getEntity()); returnContent = URLDecoder.decode(returnXML); switch (status) { @@ -57,52 +59,75 @@ public static MyMessage post(String url, String data) { message.setFlag(true); message.setMsg(returnContent); break; - + default: - Log.e("error", status+returnContent); + Log.e("error", status + returnContent); message.setFlag(false); message.setMsg(returnContent); break; } - } catch (Exception e) { + } catch (Exception e) { JSONObject jsonObject = new JSONObject(); - - try { - jsonObject.put("err", e.toString()); - returnContent = jsonObject.toString(); - message.setFlag(false); - message.setMsg(returnContent); - } catch (JSONException e1) { - e1.printStackTrace(); - } - - + + try { + jsonObject.put("err", e.toString()); + returnContent = jsonObject.toString(); + message.setFlag(false); + message.setMsg(returnContent); + } catch (JSONException e1) { + e1.printStackTrace(); + } + } CommonUtil.printLog("UMSAGENT", message.getMsg()); return message; } - + + public static String Post(String url, String data) { + + CommonUtil.printLog("ums", url); + + HttpClient httpclient = new DefaultHttpClient(); + HttpPost httppost = new HttpPost(url); + try { + StringEntity se = new StringEntity("content=" + data, HTTP.UTF_8); + CommonUtil.printLog("postdata", "content=" + data); + se.setContentType("application/x-www-form-urlencoded"); + httppost.setEntity(se); + HttpResponse response = httpclient.execute(httppost); + int status = response.getStatusLine().getStatusCode(); + CommonUtil.printLog("ums", status + ""); + String returnXML = EntityUtils.toString(response.getEntity()); + Log.d("returnString", URLDecoder.decode(returnXML)); + return URLDecoder.decode(returnXML); + + } catch (Exception e) { + CommonUtil.printLog("ums", e.toString()); + } + return null; + } + /** * compress string use gzip to reduce the size * */ - public static MyMessage postCompressed(String requestUrl,String data){ + public static MyMessage postCompressed(String requestUrl, String data) { MyMessage message = new MyMessage(); try { URL url = new URL(requestUrl); - HttpURLConnection conn = (HttpURLConnection)url.openConnection(); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); - conn.setRequestProperty("Content-encoding", "gzip"); - conn.setRequestProperty("Content-type", "application/octet-stream"); - GZIPOutputStream dos1 = new GZIPOutputStream(conn.getOutputStream()); - dos1.write(data.getBytes("utf-8")); - dos1.flush(); - dos1.close(); - if(conn.getResponseCode() == HttpStatus.SC_OK){ - message.setFlag(true); - } else { - message.setFlag(false); + conn.setRequestProperty("Content-encoding", "gzip"); + conn.setRequestProperty("Content-type", "application/octet-stream"); + GZIPOutputStream dos1 = new GZIPOutputStream(conn.getOutputStream()); + dos1.write(data.getBytes("utf-8")); + dos1.flush(); + dos1.close(); + if (conn.getResponseCode() == HttpStatus.SC_OK) { + message.setFlag(true); + } else { + message.setFlag(false); message.setMsg(conn.getResponseMessage()); - } + } } catch (Exception e) { Log.e("dakele", e.getMessage(), e); } @@ -110,8 +135,4 @@ public static MyMessage postCompressed(String requestUrl,String data){ return message; } - - - - } diff --git a/sdk/android_sdk/SDK/src/com/wbtech/ums/controller/EventController.java b/sdk/android_sdk/SDK/src/com/wbtech/ums/controller/EventController.java index b4bd2641..d07da863 100644 --- a/sdk/android_sdk/SDK/src/com/wbtech/ums/controller/EventController.java +++ b/sdk/android_sdk/SDK/src/com/wbtech/ums/controller/EventController.java @@ -1,5 +1,7 @@ package com.wbtech.ums.controller; +import org.json.JSONObject; + import android.content.Context; import android.os.Handler; @@ -11,8 +13,6 @@ import com.wbtech.ums.objects.MyMessage; import com.wbtech.ums.objects.PostObjEvent; -import org.json.JSONObject; - public class EventController { static final String EVENTURL = UmsConstants.preUrl + UmsConstants.eventUrl; From 95efa72fac36b71f4bd285b14f5fd6228d50ccf9 Mon Sep 17 00:00:00 2001 From: liyun Date: Fri, 19 Jul 2013 14:00:53 +0800 Subject: [PATCH 4/4] add new networktype;check wifi first --- .../src/com/wbtech/ums/common/CommonUtil.java | 113 +++++++++++------- 1 file changed, 73 insertions(+), 40 deletions(-) diff --git a/sdk/android_sdk/SDK/src/com/wbtech/ums/common/CommonUtil.java b/sdk/android_sdk/SDK/src/com/wbtech/ums/common/CommonUtil.java index 91510d05..660e2003 100644 --- a/sdk/android_sdk/SDK/src/com/wbtech/ums/common/CommonUtil.java +++ b/sdk/android_sdk/SDK/src/com/wbtech/ums/common/CommonUtil.java @@ -17,6 +17,10 @@ import java.util.Date; import java.util.List; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + import android.app.ActivityManager; import android.content.ComponentName; import android.content.Context; @@ -38,10 +42,6 @@ import com.wbtech.ums.objects.LatitudeAndLongitude; import com.wbtech.ums.objects.SCell; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - public class CommonUtil { public static void saveInfoToFile(Handler handler,String type, JSONObject info, Context context) { @@ -471,42 +471,75 @@ public static boolean isHaveGravity(Context context){ * @return WIFI or MOBILE */ public static String getNetworkType(Context context){ - TelephonyManager manager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); - int type= manager.getNetworkType(); - String typeString="UNKNOWN"; - if(type==TelephonyManager.NETWORK_TYPE_CDMA){ - typeString ="CDMA"; - } - if(type==TelephonyManager.NETWORK_TYPE_EDGE){ - typeString ="EDGE"; - } - if(type==TelephonyManager.NETWORK_TYPE_EVDO_0){ - typeString ="EVDO_0"; - } - if(type==TelephonyManager.NETWORK_TYPE_EVDO_A){ - typeString ="EVDO_A"; - } - if(type==TelephonyManager.NETWORK_TYPE_GPRS){ - typeString ="GPRS"; - } - if(type==TelephonyManager.NETWORK_TYPE_HSDPA){ - typeString ="HSDPA"; - } - if(type==TelephonyManager.NETWORK_TYPE_HSPA){ - typeString ="HSPA"; - } - if(type==TelephonyManager.NETWORK_TYPE_HSUPA){ - typeString ="HSUPA"; - } - if(type==TelephonyManager.NETWORK_TYPE_UMTS){ - typeString ="UMTS"; - } - if(type==TelephonyManager.NETWORK_TYPE_UNKNOWN){ - typeString ="UNKNOWN"; - } - - return typeString; - } + String typeString = "UNKNOWN"; + // check if wifi or mobile first + final ConnectivityManager connectivityManager = (ConnectivityManager) context + .getSystemService(Context.CONNECTIVITY_SERVICE); + final NetworkInfo mobNetInfoActivity = connectivityManager.getActiveNetworkInfo(); + if (mobNetInfoActivity == null || !mobNetInfoActivity.isAvailable()) { + return typeString; + } + + int netType = mobNetInfoActivity.getType(); + if (netType == ConnectivityManager.TYPE_WIFI) { + return "wifi"; + } else if (netType == ConnectivityManager.TYPE_MOBILE) { + // for mobile net + TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); + int type = manager.getNetworkType(); + + switch (type) { + case TelephonyManager.NETWORK_TYPE_GPRS: + typeString = "GPRS"; + break; + case TelephonyManager.NETWORK_TYPE_EDGE: + typeString = "EDGE"; + break; + case TelephonyManager.NETWORK_TYPE_UMTS: + typeString = "UMTS"; + break; + + case TelephonyManager.NETWORK_TYPE_CDMA: + typeString = "CDMA"; + break; + case TelephonyManager.NETWORK_TYPE_EVDO_0: + typeString = "EVDO rev. 0"; + break; + case TelephonyManager.NETWORK_TYPE_EVDO_A: + typeString = "EVDO rev. A"; + break; + case TelephonyManager.NETWORK_TYPE_1xRTT: + typeString = "1xRTT"; + break; + case TelephonyManager.NETWORK_TYPE_HSDPA: + typeString = "HSDPA"; + break; + case TelephonyManager.NETWORK_TYPE_HSUPA: + typeString = "HSUPA"; + break; + case TelephonyManager.NETWORK_TYPE_HSPA: + typeString = "HSPA"; + break; + case TelephonyManager.NETWORK_TYPE_IDEN: + typeString = "iDen"; + break; + case TelephonyManager.NETWORK_TYPE_EVDO_B: + typeString = "EVDO rev. B"; + break; + case TelephonyManager.NETWORK_TYPE_LTE: + typeString = "LTE"; + break; + case TelephonyManager.NETWORK_TYPE_EHRPD: + typeString = "eHRPD"; + break; + case TelephonyManager.NETWORK_TYPE_HSPAP: + typeString = "HSPA+"; + break; + } + + } + return typeString; + } /** * Determine the current network type * @param context