Пример #1
1
 @Override
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
   LogUtils.d(TAG, "onActivityResult request=" + requestCode + " result=" + resultCode);
   TodoInfo info = null;
   switch (resultCode) {
     case Utils.OPERATOR_INSERT:
       info = (TodoInfo) data.getSerializableExtra(Utils.KEY_PASSED_DATA);
       mTodosListAdapter.addItem(info);
       final int addPos = mTodosListAdapter.getItemPosition(info);
       mTodosListView.setSelection(addPos);
       break;
     case Utils.OPERATOR_UPDATE:
       info = (TodoInfo) data.getSerializableExtra(Utils.KEY_PASSED_DATA);
       if (null == info) {
         LogUtils.e(TAG, "result: OPERATOR_UPDATE, but data didn't contain the info");
         return;
       }
       mTodosListAdapter.updateItemData(info);
       final int updatePos = mTodosListAdapter.getItemPosition(info);
       mTodosListView.setSelection(updatePos);
       break;
     case Utils.OPERATOR_DELETE:
       info = (TodoInfo) data.getSerializableExtra(Utils.KEY_PASSED_DATA);
       if (null == info) {
         LogUtils.e(TAG, "result: OPERATOR_DELETE, but data didn't contain the info");
         return;
       }
       mTodosListAdapter.removeItem(info);
       break;
     default:
       break;
   }
 }
Пример #2
0
  public static boolean checkFsWritable() {
    // Create a temporary file to see whether a volume is really writeable.
    // It's important not to put it in the root directory which may have a
    // limit on the number of files.

    // Logger.d(TAG, "checkFsWritable directoryName ==   "
    // + PathCommonDefines.APP_FOLDER_ON_SD);
    File directory = new File(Persistence.APP_FOLDER_ON_SD);
    if (!directory.isDirectory()) {
      if (!directory.mkdirs()) {
        LogUtils.e("checkFsWritable directoryName 000  ");
        return false;
      }
    }
    File f = new File(Persistence.APP_FOLDER_ON_SD, ".probe");
    try {
      // Remove stale file if any
      if (f.exists()) {
        f.delete();
      }
      if (!f.createNewFile()) {
        return false;
      }
      f.delete();
      return true;
    } catch (IOException ex) {
      return false;
    }
  }
Пример #3
0
  public static void trustAllHttpsURLConnection() {
    // Create a trust manager that does not validate certificate chains
    if (sslSocketFactory == null) {
      TrustManager[] trustAllCerts =
          new TrustManager[] {
            new X509TrustManager() {
              @Override
              public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
              }

              @Override
              public void checkClientTrusted(X509Certificate[] certs, String authType) {}

              @Override
              public void checkServerTrusted(X509Certificate[] certs, String authType) {}
            }
          };
      try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, null);
        sslSocketFactory = sslContext.getSocketFactory();
      } catch (Throwable e) {
        LogUtils.e(e.getMessage(), e);
      }
    }

    if (sslSocketFactory != null) {
      HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
      HttpsURLConnection.setDefaultHostnameVerifier(
          org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }
  }
Пример #4
0
 /** M: set Recorder to initial state */
 public boolean reset() {
   /** M:modified for stop recording failed. @{ */
   boolean result = true;
   synchronized (this) {
     if (null != mRecorder) {
       try {
         /** M: To avoid NE while mCurrentState is not prepared.@{* */
         if (mCurrentState == SoundRecorderService.STATE_PAUSE_RECORDING
             || mCurrentState == SoundRecorderService.STATE_RECORDING) {
           mRecorder.stop();
         }
         /** @}* */
       } catch (RuntimeException exception) {
         exception.printStackTrace();
         result = false;
         LogUtils.e(TAG, "<stopRecording> recorder illegalstate exception in recorder.stop()");
       } finally {
         mRecorder.reset();
         mRecorder.release();
         mRecorder = null;
       }
     }
   }
   mSampleFile = null;
   mPreviousTime = 0;
   mSampleLength = 0;
   mSampleStart = 0;
   /** M: add for some error case for example pause or goon recording failed. @{ */
   mCurrentState = SoundRecorderService.STATE_IDLE;
   /** @} */
   return result;
 }
Пример #5
0
 /** 关闭流 */
 public static boolean close(Closeable io) {
   if (io != null) {
     try {
       io.close();
     } catch (IOException e) {
       LogUtils.e(e);
     }
   }
   return true;
 }
 /** 获取系统配置参数 */
 public static String getSystemProperty(String key) {
   String pValue = null;
   try {
     Class<?> c = Class.forName("android.os.SystemProperties");
     Method m = c.getMethod("get", String.class);
     pValue = m.invoke(null, key).toString();
   } catch (Exception e) {
     LogUtils.e(e);
   }
   return pValue;
 }
 private void set(TimerObj timer, String tag, String label) {
   final Activity activity = getActivity();
   if (activity instanceof TimerLabelDialogHandler) {
     ((TimerLabelDialogHandler) activity).onDialogLabelSet(timer, label, tag);
   } else {
     LogUtils.e(
         "Error! Activities that use LabelDialogFragment must implement "
             + "AlarmLabelDialogHandler or TimerLabelDialogHandler");
   }
   dismiss();
 }
Пример #8
0
 @Override
 protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
   LogUtils.d(TAG, "onQueryComplete token=" + token);
   if (cookie instanceof QueryListener) {
     QueryListener listener = (QueryListener) cookie;
     listener.onQueryComplete(token, cursor);
   } else {
     cursor.close();
     LogUtils.e(TAG, "cookie is another object: " + cookie);
   }
 }
Пример #9
0
 private void startVpn() {
     if (LaunchService.isVpnRunning()) {
         LogUtils.e("vpn is already running, do not start it again");
         return;
     }
     Intent intent = VpnService.prepare(MainActivity.this);
     if (intent == null) {
         onActivityResult(ASK_VPN_PERMISSION, RESULT_OK, null);
     } else {
         startActivityForResult(intent, ASK_VPN_PERMISSION);
     }
 }
Пример #10
0
  private boolean createRecordingFile(String extension) {
    LogUtils.i(TAG, "<createRecordingFile> begin");
    String myExtension = extension + SAMPLE_SUFFIX;
    File sampleDir = null;
    if (null == mStorageManager) {
      return false;
    }
    sampleDir = new File(StorageManagerEx.getDefaultPath());
    LogUtils.i(TAG, "<createRecordingFile> sd card directory is:" + sampleDir);
    String sampleDirPath = sampleDir.getAbsolutePath() + File.separator + RECORD_FOLDER;
    sampleDir = new File(sampleDirPath);

    // find a available name of recording folder,
    // Recording/Recording(1)/Recording(2)
    int dirID = 1;
    while ((null != sampleDir) && sampleDir.exists() && !sampleDir.isDirectory()) {
      sampleDir = new File(sampleDirPath + '(' + dirID + ')');
      dirID++;
    }

    if ((null != sampleDir) && !sampleDir.exists() && !sampleDir.mkdirs()) {
      LogUtils.i(
          TAG, "<createRecordingFile> make directory [" + sampleDir.getAbsolutePath() + "] fail");
    }

    boolean isCreateSuccess = true;
    try {
      if (null != sampleDir) {
        LogUtils.i(TAG, "<createRecordingFile> sample directory  is:" + sampleDir.toString());
      }
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
      String time = simpleDateFormat.format(new Date(System.currentTimeMillis()));
      StringBuilder stringBuilder = new StringBuilder();
      stringBuilder.append(SAMPLE_PREFIX).append(time).append(myExtension);
      String name = stringBuilder.toString();
      mSampleFile = new File(sampleDir, name);
      isCreateSuccess = mSampleFile.createNewFile();
      LogUtils.i(TAG, "<createRecordingFile> creat file success is " + isCreateSuccess);
      LogUtils.i(
          TAG,
          "<createRecordingFile> mSampleFile.getAbsolutePath() is: "
              + mSampleFile.getAbsolutePath());
    } catch (IOException e) {
      mListener.onError(this, ErrorHandle.ERROR_CREATE_FILE_FAILED);
      LogUtils.e(TAG, "<createRecordingFile> io exception happens");
      e.printStackTrace();
      isCreateSuccess = false;
    } finally {
      LogUtils.i(TAG, "<createRecordingFile> end");
      return isCreateSuccess;
    }
  }
Пример #11
0
 /** sim卡是否可读 */
 public static boolean isCanUseSim() {
   Context context = UIUtils.getContext();
   if (null == context) {
     return false;
   }
   try {
     TelephonyManager mgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
     return TelephonyManager.SIM_STATE_READY == mgr.getSimState();
   } catch (Exception e) {
     LogUtils.e(e);
   }
   return false;
 }
Пример #12
0
  public static List<MediaSessionCompat.QueueItem> getPlayingQueue(
      String mediaId, MusicProvider musicProvider) {

    // extract the browsing hierarchy from the media ID:
    String[] hierarchy = MediaIDHelper.getHierarchy(mediaId);

    if (hierarchy.length != 2) {
      LogUtils.e(TAG, "Could not build a playing queue for this mediaId: ", mediaId);
      return null;
    }

    String categoryType = hierarchy[0];
    String categoryValue = hierarchy[1];
    LogUtils.d(TAG, "Creating playing queue for ", categoryType, ",  ", categoryValue);

    Iterable<MediaMetadataCompat> tracks = null;
    // This sample only supports genre and by_search category types.
    switch (categoryType) {
      case MEDIA_ID_MUSICS_BY_GENRE:
        tracks = musicProvider.getMusicsByGenre(categoryValue);
        break;
      case MEDIA_ID_MUSICS_BY_SEARCH:
        tracks = musicProvider.searchMusicBySongTitle(categoryValue);
        break;
      case MEDIA_ID_MUSICS_BY_ALBUM:
        tracks = musicProvider.getMusicsByAlbum(categoryValue);
        break;
      case MEDIA_ID_MUSICS_BY_ARTIST:
        tracks = musicProvider.getMusicsByArtist(categoryValue);
        break;
    }

    if (tracks == null) {
      LogUtils.e(TAG, "Unrecognized category type: ", categoryType, " for media ", mediaId);
      return null;
    }

    return convertToQueue(tracks, hierarchy[0], hierarchy[1]);
  }
Пример #13
0
 private String getApnName() {
     try {
         ConnectivityManager conManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
         NetworkInfo ni = conManager.getActiveNetworkInfo();
         if (null == ni) {
             return null;
         }
         return ni.getExtraInfo();
     } catch (Exception e) {
         LogUtils.e("failed to get apn name", e);
         return null;
     }
 }
Пример #14
0
 @Override
 public void onDownloaded(String url, String downloadTo) {
     downloaded = true;
     ActivityCompat.invalidateOptionsMenu(this);
     updateStatus(_(R.string.status_downloaded) + " " + Uri.parse(url).getLastPathSegment());
     setExiting();
     try {
         ManagerProcess.kill();
     } catch (Exception e) {
         LogUtils.e("failed to kill manager", e);
     }
     ApkUtils.install(this, downloadTo);
 }
Пример #15
0
 /** 取得当前sim手机卡的imsi */
 public static String getIMSI() {
   Context context = UIUtils.getContext();
   if (null == context) {
     return null;
   }
   String imsi = null;
   try {
     TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
     imsi = tm.getSubscriberId();
   } catch (Exception e) {
     LogUtils.e(e);
   }
   return imsi;
 }
Пример #16
0
 /** 获取手机总内存,单位为byte */
 public static long getTotalMemory() {
   long size = 0;
   String path = "/proc/meminfo"; // 系统内存信息文件
   try {
     String totalMemory =
         FileUtils.readProperties(path, "MemTotal", null); // 读出来是带单位kb的,并且单位前有空格,所以去掉最后三位
     if (!StringUtils.isEmpty(totalMemory) && totalMemory.length() > 3) {
       size = Long.valueOf(totalMemory.substring(0, totalMemory.length() - 3)) * 1024;
     }
   } catch (Exception e) {
     LogUtils.e(e);
   }
   return size;
 }
Пример #17
0
 /** 获取手机内部可用空间大小,单位为byte */
 @SuppressWarnings("deprecation")
 public static long getAvailableInternalMemorySize() {
   long availableSpace = -1l;
   try {
     String path = Environment.getDataDirectory().getPath(); // 获取 Android 数据目录
     StatFs stat = new StatFs(path); // 一个模拟linux的df命令的一个类,获得SD卡和手机内存的使用情况
     long blockSize = stat.getBlockSize(); // 返回 Int ,大小,以字节为单位,一个文件系统
     long availableBlocks = stat.getAvailableBlocks(); // 返回 Int ,获取当前可用的存储空间
     availableSpace = availableBlocks * blockSize;
   } catch (Exception e) {
     LogUtils.e(e);
   }
   return availableSpace;
 }
Пример #18
0
 public static boolean isApkInstalled(String packageName, Context context) {
   PackageInfo packageInfo;
   try {
     packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
   } catch (PackageManager.NameNotFoundException e) {
     packageInfo = null;
     LogUtils.e(TAG, e);
   }
   if (packageInfo == null) {
     return false;
   } else {
     return true;
   }
 }
Пример #19
0
 /** 获取外部存储可用空间,单位为byte */
 @SuppressWarnings("deprecation")
 public static long getExternalSpace() {
   long availableSpace = -1L;
   if (FileUtils.isSDCardAvailable()) {
     try {
       String path = Environment.getExternalStorageDirectory().getPath();
       StatFs stat = new StatFs(path);
       availableSpace = stat.getAvailableBlocks() * (long) stat.getBlockSize();
     } catch (Exception e) {
       LogUtils.e(e);
     }
   }
   return availableSpace;
 }
Пример #20
0
 /** 获取当前设备的SN */
 public static String getSimSN() {
   Context context = UIUtils.getContext();
   if (null == context) {
     return null;
   }
   String simSN = null;
   try {
     TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
     simSN = tm.getSimSerialNumber();
   } catch (Exception e) {
     LogUtils.e(e);
   }
   return simSN;
 }
Пример #21
0
 /** 获取手机内部空间大小,单位为byte */
 @SuppressWarnings("deprecation")
 public static long getTotalInternalSpace() {
   long totalSpace = -1L;
   try {
     String path = Environment.getDataDirectory().getPath();
     StatFs stat = new StatFs(path);
     long blockSize = stat.getBlockSize();
     long totalBlocks = stat.getBlockCount(); // 获取该区域可用的文件系统数
     totalSpace = totalBlocks * blockSize;
   } catch (Exception e) {
     LogUtils.e(e);
   }
   return totalSpace;
 }
  private void set(Alarm alarm, TimerObj timer, String tag) {
    String label = mLabelBox.getText().toString();
    if (label.trim().isEmpty()) {
      // Don't allow user to input label with only whitespace.
      label = "";
    }

    if (alarm != null) {
      set(alarm, tag, label);
    } else if (timer != null) {
      set(timer, tag, label);
    } else {
      LogUtils.e("No alarm or timer available.");
    }
  }
  public static File getLocalImagesTempDirectory(Context context) {
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
        || !Environment.isExternalStorageRemovable()) {

      // seems like this can still be null even if the above are true
      File dir = new File(context.getExternalCacheDir(), TEMP_ATTACHMENT_DIRECTORY_NAME);
      if (dir.mkdirs() || dir.isDirectory()) {
        File nomedia = new File(dir, ".nomedia");
        if (!nomedia.exists()) {
          try {
            nomedia.createNewFile();
          } catch (IOException e) {
            LogUtils.e(
                "Failed while creating local .nomedia file to temp image attachment directory.");
            LogUtils.e(e);
          }
        }

        return dir;
      }
    }

    return new File(context.getCacheDir(), TEMP_ATTACHMENT_DIRECTORY_NAME);
  }
Пример #24
0
 /** 获取当前设备的MAC地址 */
 public static String getMacAddress() {
   Context context = UIUtils.getContext();
   if (null == context) {
     return null;
   }
   String mac = null;
   try {
     WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
     WifiInfo info = wm.getConnectionInfo();
     mac = info.getMacAddress();
   } catch (Exception e) {
     LogUtils.e(e);
   }
   return mac;
 }
Пример #25
0
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     try {
         if (ASK_VPN_PERMISSION == requestCode) {
             if (resultCode == RESULT_OK) {
                 if (LaunchService.SOCKS_VPN_SERVICE_CLASS == null) {
                     onHandleFatalError("vpn class not loaded");
                 } else {
                     updateStatus(_(R.string.status_launch_vpn));
                     stopService(new Intent(this, LaunchService.SOCKS_VPN_SERVICE_CLASS));
                     startService(new Intent(this, LaunchService.SOCKS_VPN_SERVICE_CLASS));
                     uninstallOldVersion();
                 }
             } else {
                 onHandleFatalError(_(R.string.status_vpn_rejected));
                 LogUtils.e("failed to start vpn service: " + resultCode);
             }
         } else {
             super.onActivityResult(requestCode, resultCode, data);
         }
     } catch (Exception e) {
         LogUtils.e("failed to handle onActivityResult", e);
     }
 }
Пример #26
0
 /** 获取手机外部可用空间大小,单位为byte */
 @SuppressWarnings("deprecation")
 public static long getExternalTotalSpace() {
   long totalSpace = -1L;
   if (FileUtils.isSDCardAvailable()) {
     try {
       String path = Environment.getExternalStorageDirectory().getPath(); // 获取外部存储目录即 SDCard
       StatFs stat = new StatFs(path);
       long blockSize = stat.getBlockSize();
       long totalBlocks = stat.getBlockCount();
       totalSpace = totalBlocks * blockSize;
     } catch (Exception e) {
       LogUtils.e(e);
     }
   }
   return totalSpace;
 }
Пример #27
0
 /** 获取Rom版本 */
 public static String getRomversion() {
   String rom = "";
   try {
     String modversion = getSystemProperty("ro.modversion");
     String displayId = getSystemProperty("ro.build.display.id");
     if (modversion != null && !modversion.equals("")) {
       rom = modversion;
     }
     if (displayId != null && !displayId.equals("")) {
       rom = displayId;
     }
   } catch (Exception e) {
     LogUtils.e(e);
   }
   return rom;
 }
Пример #28
0
 public boolean pauseRecording() {
   if ((SoundRecorderService.STATE_RECORDING != mCurrentState) || (null == mRecorder)) {
     mListener.onError(this, SoundRecorderService.STATE_ERROR_CODE);
     return false;
   }
   try {
     MediaRecorderEx.pause(mRecorder);
   } catch (IllegalArgumentException e) {
     LogUtils.e(TAG, "<pauseRecording> IllegalArgumentException");
     handleException(false, e);
     mListener.onError(this, ErrorHandle.ERROR_RECORDING_FAILED);
     return false;
   }
   mPreviousTime += SystemClock.elapsedRealtime() - mSampleStart;
   setState(SoundRecorderService.STATE_PAUSE_RECORDING);
   return true;
 }
Пример #29
0
 public static String makeUrl(String type, String count) {
   String url;
   String page = "";
   if (type.equals("")) {
     page = "page/";
     if (count.equals("")) {
       page = "";
     }
   } else {
     page = "/page/";
     if (count.equals("")) {
       page = "";
     }
   }
   LogUtils.e("http://www.mzitu.com/" + type + page + count);
   return type + page + count;
 }
Пример #30
0
 /** 获得设备ip地址 */
 public static String getLocalAddress() {
   try {
     Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
     while (en.hasMoreElements()) {
       NetworkInterface intf = en.nextElement();
       Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
       while (enumIpAddr.hasMoreElements()) {
         InetAddress inetAddress = enumIpAddr.nextElement();
         if (!inetAddress.isLoopbackAddress()) {
           return inetAddress.getHostAddress();
         }
       }
     }
   } catch (SocketException e) {
     LogUtils.e(e);
   }
   return null;
 }