Пример #1
1
  /** 初始化硬盘缓存 */
  private void initDiskCache() {
    try {
      String cache;
      if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
          || !Environment.isExternalStorageRemovable()) {
        if (context.getExternalCacheDir() != null) {
          cache = context.getExternalCacheDir().getPath();
          Log.i("Test", "SD");
        } else {
          throw new Exception("SD卡连接错误");
        }
      } else {
        cache = context.getCacheDir().getPath();
        Log.i("Test", "mobilephone");
      }

      /** SD卡数据缓存目录 */
      String dataFileName = "indoor_data";

      cache = cache + File.separator + dataFileName;
      File fileDir = new File(cache);
      if (!fileDir.exists()) {
        if (fileDir.mkdirs()) {
          Log.e("Test", "创建目录: " + fileDir.getAbsolutePath());
        } else {
          Log.e("Test", "创建目录失败");
        }
      } else {
        Log.e("Test", "目录: " + fileDir.getAbsolutePath());
      }
      diskLruCache = DiskLruCache.open(fileDir, getAppVersion(context), 1, DISK_CACHE_DEFAULT_SIZE);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #2
0
  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
      case SeventhConstants.REQUESTCODE_UPLOADAVATAR_CAMERA: // 拍照修改头像
        if (resultCode == RESULT_OK) {
          if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(UserActivity.this, "SD不可用", Toast.LENGTH_LONG).show();
            return;
          }
          isFromCamera = true;
          File file = new File(filePath);
          startImageAction(
              Uri.fromFile(file), 600, 600, SeventhConstants.REQUESTCODE_UPLOADAVATAR_CROP, true);
        }
        break;
      case SeventhConstants.REQUESTCODE_UPLOADAVATAR_LOCATION: // 本地修改头像
        if (data == null) {
          return;
        }
        if (resultCode == RESULT_OK) {
          if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(UserActivity.this, "SD不可用", Toast.LENGTH_LONG).show();
            return;
          }
          isFromCamera = false;
          // 这里传过来的是原图的url
          Uri uri = data.getData();
          startImageAction(
              uri, 600, 600, SeventhConstants.REQUESTCODE_UPLOADAVATAR_GALLERY_CROP, true);
        } else {
          Toast.makeText(UserActivity.this, "照片获取失败", Toast.LENGTH_LONG).show();
        }

        break;
      case SeventhConstants.REQUESTCODE_UPLOADAVATAR_CROP: // 相机裁剪头像返回
        if (data == null) {
          return;
        }
        // 保存图片
        saveCropAvator();
        // 初始化文件路径
        filePath = "";
        // 上传头像
        uploadAvatar();
        break;
      case SeventhConstants.REQUESTCODE_UPLOADAVATAR_GALLERY_CROP: // 相册裁剪头像返回
        if (data == null) {
          return;
        }
        // 保存图片
        saveCropAvator();
        // 初始化文件路径
        filePath = "";
        // 上传头像
        uploadAvatar();
        break;
    }
  }
 // Generate a String Array that represents all of the files found
 private String[] getTracks() {
   if (type == 0) {
     try {
       String[] temp = getAssets().list("");
       return temp;
     } catch (IOException e) {
       e.printStackTrace();
       Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
     }
   } else if (type == 1) {
     if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
         || Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
       path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
       path2 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
       String[] temp = path.list();
       return temp;
     } else {
       Toast.makeText(
               getBaseContext(),
               "SD Card is either mounted elsewhere or is unusable",
               Toast.LENGTH_LONG)
           .show();
     }
   }
   return null;
 }
 /**
  * Returns true if the SD card can be used. Otherwise, returns false.
  *
  * @return true if the SD card is available for use. Otherwie, returns false.
  */
 private boolean getSDcardStatus() {
   if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
     if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
       if (TTS.isSpeaking()) TTS.stop();
       // check if keyboard is connected but accessibility services are
       // disabled
       if (!Utils.isAccessibilityEnabled(getApplicationContext())
           && getResources().getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS)
         TTS.speak(getResources().getString(R.string.mediareadonly));
       Toast.makeText(
               getApplicationContext(),
               getResources().getString(R.string.mediareadonly),
               Toast.LENGTH_SHORT)
           .show();
       return false;
     } else {
       return true;
     }
   }
   if (TTS.isSpeaking()) TTS.stop();
   // check if keyboard is connected but accessibility services are
   // disabled
   if (!Utils.isAccessibilityEnabled(getApplicationContext())
       && getResources().getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS)
     TTS.speak(getResources().getString(R.string.mediaunmounted));
   Toast.makeText(
           getApplicationContext(),
           getResources().getString(R.string.mediaunmounted),
           Toast.LENGTH_SHORT)
       .show();
   return false;
 }
Пример #5
0
 /**
  * M: copy one file from source to target
  *
  * @author mtk54296
  * @param from source
  * @param to target
  * @return @{
  */
 private static int copyFile(String from, String to) {
   Log.v("source: " + from + "  target: " + to);
   int result = 0;
   if (TextUtils.isEmpty(from) || TextUtils.isEmpty(to)) {
     result = -1;
   }
   Log.v("media mounted: " + Environment.getExternalStorageState());
   if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
     java.io.InputStream fis = null;
     java.io.OutputStream fos = null;
     try {
       fis = new java.io.FileInputStream(from);
       fos = new java.io.FileOutputStream(to);
       byte bt[] = new byte[1024];
       int c;
       while ((c = fis.read(bt)) > 0) {
         fos.write(bt, 0, c);
       }
       fos.flush();
       fos.close();
       fis.close();
     } catch (IOException e) {
       e.printStackTrace();
       Log.v("copy ringtone file error: " + e.toString());
       result = -1;
     }
   }
   return result;
 }
Пример #6
0
  public static boolean isExternalStorageMounted() {

    boolean canRead = Environment.getExternalStorageDirectory().canRead();
    boolean onlyRead =
        Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY);
    boolean unMounted = Environment.getExternalStorageState().equals(Environment.MEDIA_UNMOUNTED);

    return !(!canRead || onlyRead || unMounted);
  }
Пример #7
0
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.menu_share:
        try {
          if (passwordList == null) return true;
          Intent i = new Intent(Intent.ACTION_SEND);
          i.setType("text/plain");
          i.putExtra(
              Intent.EXTRA_SUBJECT, keygen.getSsidName() + getString(R.string.share_msg_begin));
          final StringBuilder message = new StringBuilder(keygen.getSsidName());
          message.append(getString(R.string.share_msg_begin));
          message.append(":\n");
          for (String password : passwordList) {
            message.append(password);
            message.append('\n');
          }
          i.putExtra(Intent.EXTRA_TEXT, message.toString());
          startActivity(Intent.createChooser(i, getString(R.string.share_title)));
        } catch (Exception e) {
          Toast.makeText(getActivity(), R.string.msg_err_sendto, Toast.LENGTH_SHORT).show();
        }
        return true;
      case R.id.menu_save_sd:
        if (!Environment.getExternalStorageState().equals("mounted")
            && !Environment.getExternalStorageState().equals("mounted_ro")) {
          Toast.makeText(getActivity(), R.string.msg_nosdcard, Toast.LENGTH_SHORT).show();
          return true;
        }
        final StringBuilder message = new StringBuilder(keygen.getSsidName());
        message.append(" KEYS\n");
        for (String password : passwordList) {
          message.append(password);
          message.append('\n');
        }
        try {

          final BufferedWriter out =
              new BufferedWriter(
                  new FileWriter(folderSelect + File.separator + keygen.getSsidName() + ".txt"));
          out.write(message.toString());
          out.close();
        } catch (IOException e) {
          Toast.makeText(
                  getActivity(), getString(R.string.msg_err_saving_key_file), Toast.LENGTH_SHORT)
              .show();
          return true;
        }
        Toast.makeText(
                getActivity(),
                keygen.getSsidName() + ".txt " + getString(R.string.msg_saved_key_file),
                Toast.LENGTH_SHORT)
            .show();
        return true;
    }
    return super.onOptionsItemSelected(item);
  }
Пример #8
0
 @SuppressWarnings("unused")
 private void displayGallery() {
   if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
       && !Environment.getExternalStorageState().equals(Environment.MEDIA_CHECKING)) {
     Intent intent = new Intent();
     intent.setType("image/jpeg");
     intent.setAction(Intent.ACTION_GET_CONTENT);
     startActivityForResult(intent, Constants.REQUEST_GALLERY);
   } else {
     // Toast.make(getApplicationContext(), R.string.no_media);
   }
 }
 public static String getTotalCacheSize(Context context) throws Exception {
   long cacheSize = getFolderSize(context.getCacheDir());
   if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
     cacheSize += getFolderSize(context.getExternalCacheDir());
   }
   return getFormatSize(cacheSize);
 }
Пример #10
0
  // 将图片保存到SD卡中
  public static Uri saveImage(Bitmap bitmap) throws FileNotFoundException {
    // 先判断手机是否装有SD卡,并可以进行读写
    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
      //            Toast.makeText(getApplicationContext(),
      //                    "没有SD卡,无法保存图像.", Toast.LENGTH_SHORT).show();
      Log.e("ImagesUtil.java", "没有SD卡,无法保存图像.");
      return null;
    }

    // 获得外部SD卡,创建本应用程序的保存目录,保存相片
    File sdCard = Environment.getExternalStorageDirectory();
    File photoDir = new File(sdCard.getAbsolutePath() + "/mycamera");
    Log.i("保存图像地址", photoDir.getAbsolutePath());
    if (!photoDir.exists()) {
      photoDir.mkdirs();
    }
    File photo = new File(photoDir, (new Date()).getTime() + ".jpeg");
    FileOutputStream fOut = new FileOutputStream(photo);

    // 把数据写入文件.下面的100参数表示不压缩
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);

    // 解析图片的Uri,用它传递分享图片
    return Uri.parse("file://" + photo.getAbsolutePath());
    //        Toast.makeText(this,uri.toString(),Toast.LENGTH_LONG).show();
  }
Пример #11
0
  private void saveButtonClickedPublic() {

    Log.v("slim", "public folder path = " + Environment.getExternalStorageDirectory());

    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

      try {
        String filePath =
            Environment.getExternalStorageDirectory() + File.separator + "filename.txt";
        File file = new File(filePath);
        PrintWriter out = new PrintWriter(file);
        out.println("test write file android " + System.currentTimeMillis());
        out.close();
        // Solution 1
        // getActivity().runOnUiThread(new Runnable() {
        //    @Override
        //    public void run() {
        //        mTextView.setText("sauvegarde terminée");
        //    }
        // });
        // Solution 2
        mHandler.post(
            new Runnable() {
              @Override
              public void run() {
                mTextView.setText("sauvegarde terminée");
              }
            });

      } catch (FileNotFoundException e) {
        e.printStackTrace();
      }
    }
  }
Пример #12
0
  @Override
  public void start() {
    mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
    final boolean connected = mStorageManager.isUsbMassStorageConnected();
    if (DEBUG)
      Log.d(
          TAG,
          String.format(
              "Startup with UMS connection %s (media state %s)",
              mUmsAvailable, Environment.getExternalStorageState()));

    HandlerThread thr = new HandlerThread("SystemUI StorageNotification");
    thr.start();
    mAsyncEventHandler = new Handler(thr.getLooper());

    if (GN_USB_SUPPORT && isFirstBoot()) {
      setToMtpByDefault();
    }

    mStorageEventlistener = new StorageNotificationEventListener();
    mStorageEventlistener.onUsbMassStorageConnectionChanged(connected);
    mStorageManager.registerListener(mStorageEventlistener);

    IntentFilter filter = new IntentFilter();
    filter.addAction(UsbManager.ACTION_USB_STATE);
    mContext.registerReceiver(mUsbStateReceiver, filter);
  }
Пример #13
0
 public static String getImageFolder(String imageType) {
   String tempFolder = SheJiaoMaoApplication.getSdcardCachePath() + File.separator + imageType;
   if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
     tempFolder = SheJiaoMaoApplication.getInnerCachePath() + File.separator + imageType;
   }
   return tempFolder;
 }
Пример #14
0
 public static final boolean sdCardMounted(final Context context) {
   if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
     Toast.makeText(context, "SD card is not available...", Toast.LENGTH_SHORT).show();
     return false;
   }
   return true;
 }
Пример #15
0
    /**
     * 计算存储目录下的文件大小, 当文件总大小大于规定的CACHE_SIZE或者sdcard剩余空间小于FREE_SD_SPACE_NEEDED_TO_CACHE的规定
     * 那么删除40%最近没有被使用的文件
     */
    private boolean removeCache(String dirPath) {
      File dir = new File(dirPath);
      File[] files = dir.listFiles();
      if (files == null) {
        return true;
      }
      if (!android.os.Environment.getExternalStorageState()
          .equals(android.os.Environment.MEDIA_MOUNTED)) {
        return false;
      }

      int dirSize = 0;
      for (int i = 0; i < files.length; i++) {
        if (files[i].getName().contains(WHOLESALE_CONV)) {
          dirSize += files[i].length();
        }
      }

      if (dirSize > CACHE_SIZE * MB || FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd()) {
        int removeFactor = (int) ((0.4 * files.length) + 1);
        Arrays.sort(files, new FileLastModifSort());
        for (int i = 0; i < removeFactor; i++) {
          if (files[i].getName().contains(WHOLESALE_CONV)) {
            files[i].delete();
          }
        }
      }

      if (freeSpaceOnSd() <= CACHE_SIZE) {
        return false;
      }

      return true;
    }
Пример #16
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // mounted sdcard ?
    if (!Environment.getExternalStorageState().equals("mounted")) {
      Log.e(GlobalConstants.LOG_TAG, "External storage is not mounted");

      Toast toast =
          Toast.makeText(
              getApplicationContext(), "External storage not mounted", Toast.LENGTH_LONG);
      toast.show();
      return;
    }

    // install needed ?
    boolean installNeeded = isInstallNeeded();

    if (installNeeded) {
      setContentView(R.layout.install);
      new InstallAsyncTask().execute();
    } else {
      runScriptService();
      finish();
    }

    // onStart();
  }
Пример #17
0
  private void initImageLoader() {
    DisplayImageOptions options =
        new DisplayImageOptions.Builder()
            .bitmapConfig(Bitmap.Config.RGB_565)
            .imageScaleType(ImageScaleType.EXACTLY)
            .cacheOnDisc(true)
            .displayer(new FadeInBitmapDisplayer(200))
            .showImageOnLoading(R.drawable.ic_avatar)
            .build();

    File cacheDir;
    if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
      cacheDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    } else {
      cacheDir = getCacheDir();
    }
    ImageLoaderConfiguration.Builder configBuilder =
        new ImageLoaderConfiguration.Builder(mContext)
            .threadPoolSize(2)
            .memoryCache(new WeakMemoryCache())
            .denyCacheImageMultipleSizesInMemory()
            .discCache(new UnlimitedDiscCache(cacheDir))
            .defaultDisplayImageOptions(options);
    if (BuildConfig.DEBUG) {
      configBuilder.writeDebugLogs();
    }
    ImageLoader.getInstance().init(configBuilder.build());
  }
Пример #18
0
 public static boolean isExternalStorageWritable() {
   String state = Environment.getExternalStorageState();
   if (Environment.MEDIA_MOUNTED.equals(state)) {
     return true;
   }
   return false;
 }
Пример #19
0
  @Override
  public void onReceive(Context context, Intent intent) {
    // make sure sd card is ready, if not don't try to send
    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
      return;
    }

    String action = intent.getAction();
    ConnectivityManager manager =
        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo currentNetworkInfo = manager.getActiveNetworkInfo();

    if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
      if (currentNetworkInfo != null
          && currentNetworkInfo.getState() == NetworkInfo.State.CONNECTED) {
        if (interfaceIsEnabled(context, currentNetworkInfo)) {
          uploadForms(context);
        }
      }
    } else if (action.equals("com.geoodk.collect.android.FormSaved")) {
      ConnectivityManager connectivityManager =
          (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo ni = connectivityManager.getActiveNetworkInfo();

      if (ni == null || !ni.isConnected()) {
        // not connected, do nothing
      } else {
        if (interfaceIsEnabled(context, ni)) {
          uploadForms(context);
        }
      }
    }
  }
Пример #20
0
 private void printError(
     int errorCode, String description, String failingUrl, WWidgetData errorWgt) {
   try {
     DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
     String time = formatter.format(new Date());
     String fileName = time + ".log";
     if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
       String ePath = Environment.getExternalStorageDirectory().getAbsolutePath();
       String path = ePath + "/widgetone/log/pageloaderror/";
       File dir = new File(path);
       if (!dir.exists()) {
         dir.mkdirs();
       }
       StringBuffer sb = new StringBuffer();
       sb.append("failingDes: " + description);
       sb.append("\n");
       sb.append("failingUrl: " + failingUrl);
       sb.append("\n");
       sb.append("errorCode: " + errorCode);
       sb.append("\n");
       if (null != errorWgt) {
         sb.append(errorWgt.toString());
       }
       FileOutputStream fos = new FileOutputStream(path + fileName);
       fos.write(sb.toString().getBytes());
       fos.flush();
       fos.close();
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Пример #21
0
  /**
   * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
   *
   * @param context A {@link Context} to use for creating the cache dir.
   * @param stack An {@link HttpStack} to use for the network, or null for default.
   * @return A started {@link RequestQueue} instance.
   */
  public synchronized void init(Context context, HttpStack stack) {
    File cacheDir = null;
    String status = Environment.getExternalStorageState();
    if (status.equals(Environment.MEDIA_MOUNTED) && context.getExternalCacheDir().exists())
      cacheDir = new File(context.getExternalCacheDir(), DEFAULT_CACHE_DIR);
    else cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
    String userAgent = "com.sohu.focus";
    try {
      String packageName = context.getPackageName();
      PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
      userAgent = packageName + "Android/v_" + info.versionCode + ",build/" + Build.VERSION.RELEASE;
    } catch (NameNotFoundException e) {
    }

    if (stack == null) {
      if (Build.VERSION.SDK_INT >= 9) {
        stack = new HurlStack();
      } else {
        stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
      }
    }
    diskCache = new DiskBasedCache(cacheDir);
    Network network = new BasicNetwork(stack);
    queue = new RequestQueue(diskCache, network);
    queue.start();

    int memoryCacheSize = (int) (Runtime.getRuntime().maxMemory() / 8);
    memoryCache = new LruMemoryCache(memoryCacheSize);
    imageLoader = new ImageLoader(queue, memoryCache);
  }
Пример #22
0
  /**
   * 短信的备份
   *
   * @param view
   */
  public void smsBackup(View view) {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
      final File file = new File(Environment.getExternalStorageDirectory(), "smsbackup.xml");
      final ProgressDialog pd = new ProgressDialog(this);
      pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
      pd.setMessage("稍安勿躁,正在备份中...");
      pd.show();
      new Thread() {
        public void run() {
          try {
            SmsTools.backup(
                getApplicationContext(),
                file.getAbsolutePath(),
                new BackUpCallBack() {
                  @Override
                  public void onSmsBackup(int progress) {
                    pd.setProgress(progress);
                  }

                  @Override
                  public void beforeSmsBackup(int total) {
                    pd.setMax(total);
                  }
                });
          } catch (Exception e) {
            e.printStackTrace();
          }
          pd.dismiss();
        };
      }.start();
    } else {
      Toast.makeText(this, "sd不可用", 0).show();
    }
  }
Пример #23
0
 private void qaulOpenFile(String myPath) {
   // check if sdcard is mounted
   if (android.os.Environment.getExternalStorageState()
       .equals(android.os.Environment.MEDIA_MOUNTED)) {
     // check if location on sdcard exists
     String myDirPath = "/sdcard/qaul";
     File myDir = new File(myDirPath);
     if (myDir.exists() == false) {
       if (!myDir.mkdir()) {
         Log.d(MSG_TAG, "ERROR: unable to create " + myDirPath);
       }
     }
     if (myDir.exists()) {
       // check if file exists on sdcard
       String myNewPath = myDirPath + "/" + myPath.substring(myPath.lastIndexOf("/") + 1);
       File myNewFile = new File(myNewPath);
       if (myNewFile.exists() == false) {
         // copy file to sdcard
         File mySrcFile = new File(myPath);
         this.qaulCopyFile(mySrcFile, myNewFile);
       }
       if (myNewFile.exists()) {
         // open file
         Log.d(MSG_TAG, "Calling qaulOpenFile() " + myPath);
         if (myMainActivity != null) {
           Log.d(MSG_TAG, "QaulActivity reference set");
           myMainActivity.openFile(myNewFile);
         }
       }
     }
   }
 }
Пример #24
0
 public asyncSaveDmesg(
     Activity clientActivity, List<DmesgLine> list, MenuItem item, boolean blnShare) {
   this.mActivity = clientActivity;
   this.mProgressDlg = new ProgressDialog(this.mActivity);
   this.mListDmesgs = list;
   this.mItem = item;
   this.mBlnShare = blnShare; // Are we sharing or saving?
   String sdState = android.os.Environment.getExternalStorageState();
   if (sdState.equals(android.os.Environment.MEDIA_MOUNTED)) {
     this.mFExternalSDCard = android.os.Environment.getExternalStorageDirectory();
     this.mStrFullPath =
         String.format(
             "%s/%s",
             mFExternalSDCard.getPath(),
             mStrDropFolder.substring(
                 0, mStrDropFolder.length() - 1)); // chop off trailing slash
     this.mFSDCardPath = new File(this.mStrFullPath);
     if (!this.mFSDCardPath.exists()) {
       if (!this.mFSDCardPath.mkdirs()) {
         // Red Alert....
         Log.w(TAG, String.format("Unable to create %s", this.mStrFullPath));
       }
     }
   }
 }
Пример #25
0
 /** true-当前sd卡可用,false不可用 */
 public static boolean checkSdCardIsOk() {
   if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
     return true;
   } else {
     return false;
   }
 }
Пример #26
0
  private void exportTokenFile() {
    SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    String token = p.getString("token", null);

    if (token == null) {
      Toast.makeText(
              getBaseContext(),
              "You have to import a token, before you can export it.",
              Toast.LENGTH_LONG)
          .show();
      return;
    }

    String state = Environment.getExternalStorageState();

    if (state.equals(Environment.MEDIA_MOUNTED)) {
      try {
        FileWriter fw = new FileWriter(tokenFile());
        BufferedWriter out = new BufferedWriter(fw);
        out.write(token);
        out.newLine();
        out.close();
        fw.close();

        Toast.makeText(getBaseContext(), "Token exported as token.txt.", Toast.LENGTH_LONG).show();
        return;
      } catch (IOException e) {
        Log.e(TAG, "IO Exception during token export: " + e);
      }
    }

    Toast.makeText(getBaseContext(), "Could not write token file.", Toast.LENGTH_LONG).show();
  }
Пример #27
0
  @Override
  public void uncaughtException(Thread thread, Throwable ex) {

    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);

    // Inject some info about android version and the device, since google can't provide them in the
    // developer console
    StackTraceElement[] trace = ex.getStackTrace();
    StackTraceElement[] trace2 = new StackTraceElement[trace.length + 3];
    System.arraycopy(trace, 0, trace2, 0, trace.length);
    trace2[trace.length + 0] =
        new StackTraceElement("Android", "MODEL", android.os.Build.MODEL, -1);
    trace2[trace.length + 1] =
        new StackTraceElement("Android", "VERSION", android.os.Build.VERSION.RELEASE, -1);
    trace2[trace.length + 2] =
        new StackTraceElement("Android", "FINGERPRINT", android.os.Build.FINGERPRINT, -1);
    ex.setStackTrace(trace2);

    ex.printStackTrace(printWriter);
    String stacktrace = result.toString();
    printWriter.close();
    Log.e(TAG, stacktrace);

    // Save the log on SD card if available
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
      String sdcardPath = Environment.getExternalStorageDirectory().getPath();
      writeLog(stacktrace, sdcardPath + "/vlc_crash");
      writeLogcat(sdcardPath + "/vlc_logcat");
    }

    defaultUEH.uncaughtException(thread, ex);
  }
Пример #28
0
  /** 获得数据库路径 */
  @Override
  public File getDatabasePath(String name) {
    File dbFile = null;

    boolean sdExist =
        android.os.Environment.getExternalStorageState()
            .equals(android.os.Environment.MEDIA_MOUNTED);
    if (!sdExist) {
      Log.e(TAG, "SDCard does not exist !");
    } else {
      /* 生成数据库路径 */
      String dbDir = Environment.getExternalStorageDirectory().toString(); // 获取跟目录
      String dbPath = dbDir + "/" + name;
      File dirFile = new File(dbDir);
      if (!dirFile.exists()) {
        dirFile.mkdirs();
      }

      dbFile = new File(dbPath);
      if (!dbFile.exists()) {
        try {
          /* 不存在则创建数据库文件 */
          dbFile.createNewFile();
        } catch (IOException e) {
          e.printStackTrace();
          dbFile = null;
        }
      }
    }
    return dbFile;
  }
Пример #29
0
 /**
  * Check the external storage status
  *
  * @return
  */
 private boolean isExternalStorageAvilable() {
   String state = Environment.getExternalStorageState();
   if (Environment.MEDIA_MOUNTED.equals(state)) {
     return true;
   }
   return false;
 }
Пример #30
0
	@Override
	public boolean onPrepareOptionsMenu(Menu menu)
	{
		super.onPrepareOptionsMenu(menu);
		//Log.e("Navit","onPrepareOptionsMenu");
		// this gets called every time the menu is opened!!
		// change menu items here!
		menu.clear();

		// group-id,item-id,sort order number
		//menu.add(1, 1, 100, getString(R.string.optionsmenu_zoom_in)); //TRANS
		//menu.add(1, 2, 200, getString(R.string.optionsmenu_zoom_out)); //TRANS

		menu.add(1, 3, 300, getString(R.string.optionsmenu_download_maps)); //TRANS
		menu.add(1, 5, 400, getString(R.string.optionsmenu_toggle_poi)); //TRANS

		menu.add(1, 6, 500, getString(R.string.optionsmenu_address_search)); //TRANS
		menu.add(1, 10, 600, getString(R.string.optionsmenu_set_map_location));

		menu.add(1, 99, 900, getString(R.string.optionsmenu_exit_navit)); //TRANS
		
		/* Only show the Backup to SD-Card Option if we really have one */
		if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
		    menu.add(1, 7, 700, getString(R.string.optionsmenu_backup_restore)); //TRANS
		
		return true;
	}