/**
  * 发起PUT请求
  *
  * @param link URL
  * @param datas 传递给服务器的参数
  * @return API返回JSON数据
  * @throws Exception 异常
  */
 private JSONObject put(String link, Object datas) throws Exception {
   LogUtil.i("HTTP.PUT", link);
   //        StringBuffer data = new StringBuffer();
   //        if (datas != null) {
   //            Iterator<Map.Entry<String, Object>> it = datas.entrySet().iterator();
   //            while (it.hasNext()) {
   //                Map.Entry<String, Object> pairs = it.next();
   //                if (pairs.getValue() instanceof Object[]) {
   //                    for (Object d : (Object[]) pairs.getValue()) {
   //                        data.append("&" + pairs.getKey() + "=" + d.toString());
   //                    }
   //                } else if (pairs.getValue() instanceof Collection) {
   //                    for (Object d : (Collection) pairs.getValue()) {
   //                        data.append("&" + pairs.getKey() + "=" + d.toString());
   //                    }
   //                } else {
   //                    data.append("&" + pairs.getKey() + "=" + pairs.getValue().toString());
   //                }
   //            }
   //        }
   String data = "";
   if (datas instanceof Map) {
     JSONObject json = new JSONObject((Map) datas);
     data = json.toString();
   } else if (datas instanceof JSONObject) {
     data = datas.toString();
   }
   LogUtil.i("HTTP.PUT", data);
   URL url = new URL(link);
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("PUT");
   if (token != null) {
     conn.setRequestProperty("token", token);
     LogUtil.i("HTTP.PUT", token);
   }
   conn.setRequestProperty("Content-Type", "application/json");
   conn.setReadTimeout(5000);
   conn.setConnectTimeout(10000);
   conn.setDoInput(true);
   conn.setDoOutput(true);
   OutputStream out = conn.getOutputStream();
   out.write(data.getBytes());
   out.flush();
   out.close();
   InputStream is = conn.getResponseCode() >= 400 ? conn.getErrorStream() : conn.getInputStream();
   ByteArrayOutputStream os = new ByteArrayOutputStream();
   int len;
   byte buffer[] = new byte[1024];
   while ((len = is.read(buffer)) != -1) {
     os.write(buffer, 0, len);
   }
   is.close();
   os.close();
   conn.disconnect();
   String content = new String(os.toByteArray());
   LogUtil.i("HTTP.PUT", content);
   JSONObject jsonObject = new JSONObject(content);
   checkCode(jsonObject);
   return jsonObject;
 }
 /**
  * 发起GET请求
  *
  * @param link URL
  * @return API返回JSON数据
  * @throws Exception 异常
  */
 private JSONObject get(String link) throws Exception {
   LogUtil.i("HTTP.GET", link);
   URL url = new URL(link);
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("GET");
   // conn.setRequestProperty("User-agent", "Mozilla/5.0 (Linux; Android 4.2.1; Nexus 7
   // Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166  Safari/535.19");
   conn.setReadTimeout(5000);
   conn.setConnectTimeout(10000);
   if (token != null) {
     conn.setRequestProperty("token", token);
     LogUtil.i("HTTP.GET", token);
   }
   InputStream is = conn.getResponseCode() >= 400 ? conn.getErrorStream() : conn.getInputStream();
   ByteArrayOutputStream os = new ByteArrayOutputStream();
   int len;
   byte buffer[] = new byte[1024];
   while ((len = is.read(buffer)) != -1) {
     os.write(buffer, 0, len);
   }
   is.close();
   os.close();
   conn.disconnect();
   String content = new String(os.toByteArray());
   LogUtil.i("HTTP.GET", content);
   JSONObject jsonObject = new JSONObject(content);
   checkCode(jsonObject);
   return jsonObject;
 }
 /** 使用Gson解析服务器返回的JSON数据,并将解析的数据存储到本地 */
 public static void handleWeatherResponse(Context context, String response) {
   try {
     LogUtil.i("UTILITY", "----------------->" + response.toString());
     Gson gson = new Gson();
     Weather weather = gson.fromJson(response, Weather.class);
     LogUtil.i("UTILITY", "----------------->" + weather.toString());
     Weatherinfo info = weather.getWeatherinfo();
     LogUtil.i("UTILITY", "----------------->" + info.toString());
     saveWeatherInfo(context, info);
   } catch (Exception e) {
     // TODO: handle exception
   }
 }
  /** 将服务器返回的天气信息存储到共享参数中 */
  public static void saveWeatherInfo(Context context, Weatherinfo info) {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日", Locale.CHINA);
    SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
    editor.putBoolean("city_selected", true);
    editor.putString("city_name", info.getCity());
    editor.putString("weather_code", info.getCityid());
    editor.putString("temp1", info.getTemp1());
    editor.putString("temp2", info.getTemp2());
    editor.putString("weather_desp", info.getWeather());
    editor.putString("publish_time", info.getPtime());
    LogUtil.i("UTILITY", "----------------->" + sdf.format(new Date()));
    editor.putString("current_date", sdf.format(new Date()));
    editor.commit();
  }
Beispiel #5
0
  /**
   * 获取服务是否开启
   *
   * @param context
   * @param className 服务的全类名
   * @return 服务开启的状态
   */
  public static boolean isRunningService(Context context, String className) {
    boolean isRunning = false;
    // 这里是进程的管理者,活动的管理者
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    // 获取正在运行的服务,maxNum:上限值,如果小于上限值有多少返回多少,大于只返回上限值个数的服务
    List<ActivityManager.RunningServiceInfo> serviceInfos = am.getRunningServices(1000);
    // 遍历集合
    for (ActivityManager.RunningServiceInfo serviceInfo : serviceInfos) {
      // 先得到service component 再通过getClassName得打组件的全类名,这里不是getPackageName,因为一个应用有多个服务
      ComponentName component_Name = serviceInfo.service;
      // 获取服务全类名
      String componentName = component_Name.getClassName();

      // 判断获取类名和传递进来的类名是否一致,一致返回true表示正在运行,不一致返回false表示没有运行
      if (!TextUtils.isEmpty(className) && className.equals(componentName)) {
        // 如果包含该服务,说明服务已经开启了
        isRunning = true;
        LogUtil.i(TAG, "service is running:" + isRunning);
      }
    }
    return isRunning;
  }
  @TargetApi(Build.VERSION_CODES.HONEYCOMB)
  public static Bitmap extractThumbNail(
      final String path, final int width, final int height, final boolean crop) {
    Assert.assertTrue(path != null && !path.equals("") && height > 0 && width > 0);

    BitmapFactory.Options options = new BitmapFactory.Options();

    try {
      options.inJustDecodeBounds = true;
      Bitmap tmp = BitmapFactory.decodeFile(path, options);
      if (tmp != null) {
        tmp.recycle();
        tmp = null;
      }

      LogUtil.d(TAG, "extractThumbNail: round=" + width + "x" + height + ", crop=" + crop);
      final double beY = options.outHeight * 1.0 / height;
      final double beX = options.outWidth * 1.0 / width;
      LogUtil.d(TAG, "extractThumbNail: extract beX = " + beX + ", beY = " + beY);
      options.inSampleSize = (int) (crop ? (beY > beX ? beX : beY) : (beY < beX ? beX : beY));
      if (options.inSampleSize <= 1) {
        options.inSampleSize = 1;
      }

      // NOTE: out of memory error
      while (options.outHeight * options.outWidth / options.inSampleSize
          > MAX_DECODE_PICTURE_SIZE) {
        options.inSampleSize++;
      }

      int newHeight = height;
      int newWidth = width;
      if (crop) {
        if (beY > beX) {
          newHeight = (int) (newWidth * 1.0 * options.outHeight / options.outWidth);
        } else {
          newWidth = (int) (newHeight * 1.0 * options.outWidth / options.outHeight);
        }
      } else {
        if (beY < beX) {
          newHeight = (int) (newWidth * 1.0 * options.outHeight / options.outWidth);
        } else {
          newWidth = (int) (newHeight * 1.0 * options.outWidth / options.outHeight);
        }
      }

      options.inJustDecodeBounds = false;
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        options.inMutable = true;
      }
      LogUtil.i(
          TAG,
          "bitmap required size="
              + newWidth
              + "x"
              + newHeight
              + ", orig="
              + options.outWidth
              + "x"
              + options.outHeight
              + ", sample="
              + options.inSampleSize);
      Bitmap bm = BitmapFactory.decodeFile(path, options);
      setInNativeAlloc(options);
      if (bm == null) {
        Log.e(TAG, "bitmap decode failed");
        return null;
      }

      LogUtil.i(TAG, "bitmap decoded size=" + bm.getWidth() + "x" + bm.getHeight());
      final Bitmap scale = Bitmap.createScaledBitmap(bm, newWidth, newHeight, true);
      if (scale != null) {
        bm.recycle();
        bm = scale;
      }

      if (crop) {
        final Bitmap cropped =
            Bitmap.createBitmap(
                bm, (bm.getWidth() - width) >> 1, (bm.getHeight() - height) >> 1, width, height);
        if (cropped == null) {
          return bm;
        }

        bm.recycle();
        bm = cropped;
        LogUtil.i(TAG, "bitmap croped size=" + bm.getWidth() + "x" + bm.getHeight());
      }
      return bm;

    } catch (final OutOfMemoryError e) {
      LogUtil.e(TAG, "decode bitmap failed: " + e.getMessage());
      options = null;
    }

    return null;
  }
 /**
  * 上传文件
  *
  * @param token 用户令牌
  * @param file 上传文件
  * @param type 上传类型 1:头像,2:日志
  * @return API返回JSON数据
  * @throws Exception 异常
  */
 public JSONObject upload(String token, File file, int type) throws Exception {
   int TIME_OUT = 10 * 1000;
   String CHARSET = "utf-8";
   String BOUNDARY = UUID.randomUUID().toString();
   String PREFIX = "--", LINE_END = "\r\n";
   String CONTENT_TYPE = "multipart/form-data";
   URL url = null;
   if (type == 1) {
     url = new URL(AppConfig.API_DOMAIN + "/api/user/upload");
   } else {
     url = new URL(AppConfig.API_DOMAIN + "/api/crush/");
   }
   LogUtil.i("HTTP.upload", url.toString());
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   conn.setReadTimeout(TIME_OUT);
   conn.setConnectTimeout(TIME_OUT);
   conn.setDoInput(true);
   conn.setDoOutput(true);
   conn.setUseCaches(false);
   conn.setRequestProperty("token", token);
   conn.setRequestMethod("POST");
   conn.setRequestProperty("Charset", CHARSET);
   conn.setRequestProperty("connection", "keep-alive");
   conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
   DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
   StringBuffer sb = new StringBuffer();
   sb.append(PREFIX);
   sb.append(BOUNDARY);
   sb.append(LINE_END);
   sb.append(
       "Content-Disposition: form-data; name=\"file\"; filename=\""
           + file.getName()
           + "\""
           + LINE_END);
   sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
   sb.append(LINE_END);
   dos.write(sb.toString().getBytes());
   InputStream is = new FileInputStream(file);
   byte[] bytes = new byte[1024];
   int len = 0;
   while ((len = is.read(bytes)) != -1) {
     dos.write(bytes, 0, len);
   }
   is.close();
   dos.write(LINE_END.getBytes());
   byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
   dos.write(end_data);
   dos.flush();
   is = conn.getResponseCode() >= 400 ? conn.getErrorStream() : conn.getInputStream();
   ByteArrayOutputStream os = new ByteArrayOutputStream();
   byte buffer[] = new byte[1024];
   while ((len = is.read(buffer)) != -1) {
     os.write(buffer, 0, len);
   }
   is.close();
   os.close();
   conn.disconnect();
   String content = new String(os.toByteArray());
   LogUtil.i("HTTP.upload", content);
   JSONObject jsonObject = new JSONObject(content);
   return jsonObject;
 }
Beispiel #8
0
 public static int begin(String sipId, String msg) {
   String[] classMethod = CommonUtil.getClassMethod(new Exception(), "CallLog", "begin");
   return LogUtil.i(classMethod[0], classMethod[1], sipId, LogUtil.LOG_BEGIN, msg);
 }
Beispiel #9
0
 public static int end(String sipId, String msg) {
   String[] classMethod = CommonUtil.getClassMethod(new Exception(), "CallLog", "end");
   return LogUtil.i(classMethod[0], classMethod[1], sipId, LogUtil.LOG_END, msg);
 }