/** * 获取手机内置存储总的存储空间 * * @return */ public static long getTotalInternalSystemMemorySize() { File path = Environment.getRootDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long totalBlocks = stat.getBlockCount(); return totalBlocks * blockSize; }
public long BusyMemory() { StatFs statFs = new StatFs(Environment.getRootDirectory().getAbsolutePath()); long Total = (statFs.getBlockCount() * statFs.getBlockSize()) / MB; long Free = (statFs.getAvailableBlocks() * statFs.getBlockSize()) / MB; long Busy = Total - Free; return Busy; }
/** * 获取手机内置存储剩余存储空间 * * @return */ public static long getAvailableInternalSystemMemorySize() { File path = Environment.getRootDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); return availableBlocks * blockSize; }
private String[] findFonts() { ArrayList<File> dirs = new ArrayList<File>(); File[] dataDirs = getDataDirectories("fonts", false, false); for (File dir : dataDirs) dirs.add(dir); File[] rootDirs = getStorageDirectories(false); for (File dir : rootDirs) dirs.add(new File(dir, "fonts")); dirs.add(new File(Environment.getRootDirectory(), "fonts")); ArrayList<String> fontPaths = new ArrayList<String>(); for (File fontDir : dirs) { if (fontDir.isDirectory()) { log.v("Scanning directory " + fontDir.getAbsolutePath() + " for font files"); // get font names String[] fileList = fontDir.list( new FilenameFilter() { public boolean accept(File dir, String filename) { String lc = filename.toLowerCase(); return (lc.endsWith(".ttf") || lc.endsWith(".otf") || lc.endsWith(".pfb") || lc.endsWith(".pfa")) // && !filename.endsWith("Fallback.ttf") ; } }); // append path for (int i = 0; i < fileList.length; i++) { String pathName = new File(fontDir, fileList[i]).getAbsolutePath(); fontPaths.add(pathName); log.v("found font: " + pathName); } } } return fontPaths.toArray(new String[] {}); }
private void loadSpnOverrides() { FileReader spnReader; File spnFile = new File(Environment.getRootDirectory(), PARTNER_SPN_OVERRIDE_PATH); File oemSpnFile = new File(Environment.getOemDirectory(), OEM_SPN_OVERRIDE_PATH); if (oemSpnFile.exists()) { // OEM image exist SPN xml, get the timestamp from OEM & System image for comparison. long oemSpnTime = oemSpnFile.lastModified(); long sysSpnTime = spnFile.lastModified(); Rlog.d(LOG_TAG, "SPN Timestamp: oemTime = " + oemSpnTime + " sysTime = " + sysSpnTime); // To get the newer version of SPN from OEM image if (oemSpnTime > sysSpnTime) { Rlog.d(LOG_TAG, "SPN in OEM image is newer than System image"); spnFile = oemSpnFile; } } else { // No SPN in OEM image, so load it from system image. Rlog.d( LOG_TAG, "No SPN in OEM image = " + oemSpnFile.getPath() + " Load SPN from system image"); } try { spnReader = new FileReader(spnFile); } catch (FileNotFoundException e) { Rlog.w(LOG_TAG, "Can not open " + spnFile.getAbsolutePath()); return; } try { XmlPullParser parser = Xml.newPullParser(); parser.setInput(spnReader); XmlUtils.beginDocument(parser, "spnOverrides"); while (true) { XmlUtils.nextElement(parser); String name = parser.getName(); if (!"spnOverride".equals(name)) { break; } String numeric = parser.getAttributeValue(null, "numeric"); String data = parser.getAttributeValue(null, "spn"); mCarrierSpnMap.put(numeric, data); } spnReader.close(); } catch (XmlPullParserException e) { Rlog.w(LOG_TAG, "Exception in spn-conf parser " + e); } catch (IOException e) { Rlog.w(LOG_TAG, "Exception in spn-conf parser " + e); } }
/** * 获得图片缓存路径 * * @return */ public static String getAppDir() { if (appDir == null) { if (SysUtil.isSdExist()) { appDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/One"; } else { appDir = Environment.getRootDirectory().getAbsolutePath() + "/One"; } } else { File file = new File(appDir); if (!file.exists()) { file.mkdirs(); } } return appDir; }
@Override protected Void doInBackground(Void... params) { // note to future_me: yea one thinks we only need to search root here, but root was /system // for me and so // did not contain "/SDCARD" #dontoptimize // on my phone: // search in /system // (26110): search in /mnt/sdcard // (26110): search in /cache // (26110): search in /data search_in(Environment.getRootDirectory().toString()); search_in(Environment.getExternalStorageDirectory().toString()); search_in(Environment.getDownloadCacheDirectory().toString()); search_in(Environment.getDataDirectory().toString()); return null; }
protected Long doInBackground(String... vals) { FileManager flmg = new FileManager(getBaseContext()); File dir = new File(vals[0]); long size = 0; int len = 0; File[] list = dir.listFiles(); if (list != null) len = list.length; for (int i = 0; i < len; i++) { if (list[i].isFile()) mFileCount++; else if (list[i].isDirectory()) mDirCount++; } if (vals[0].equals("/")) { StatFs fss = new StatFs(Environment.getRootDirectory().getPath()); size = fss.getAvailableBlocks() * (fss.getBlockSize() / KB); mDisplaySize = (size > GB) ? String.format("%.2f Gb ", (double) size / MG) : String.format("%.2f Mb ", (double) size / KB); } else if (vals[0].equals("/sdcard")) { StatFs fs = new StatFs(Environment.getExternalStorageDirectory().getPath()); size = fs.getBlockCount() * (fs.getBlockSize() / KB); mDisplaySize = (size > GB) ? String.format("%.2f Gb ", (double) size / GB) : String.format("%.2f Gb ", (double) size / MG); } else { size = flmg.getDirSize(vals[0]); if (size > GB) mDisplaySize = String.format("%.2f Gb ", (double) size / GB); else if (size < GB && size > MG) mDisplaySize = String.format("%.2f Mb ", (double) size / MG); else if (size < MG && size > KB) mDisplaySize = String.format("%.2f Kb ", (double) size / KB); else mDisplaySize = String.format("%.2f bytes ", (double) size); } return size; }
public void mOnClick(View v) { switch (v.getId()) { case R.id.test: String rootdir = Environment.getRootDirectory().getAbsolutePath(); String datadir = Environment.getDataDirectory().getAbsolutePath(); String cachedir = Environment.getDownloadCacheDirectory().getAbsolutePath(); mEdit.setText( String.format( "ext = %s\nroot=%s\ndata=%s\ncache=%s", mSdPath, rootdir, datadir, cachedir)); break; case R.id.save: File dir = new File(mSdPath + "/dir"); dir.mkdir(); File file = new File(mSdPath + "/dir/file.txt"); try { FileOutputStream fos = new FileOutputStream(file); String str = "This file exists in SDcard"; fos.write(str.getBytes()); fos.close(); mEdit.setText("write success"); } catch (FileNotFoundException e) { mEdit.setText("File Not Found." + e.getMessage()); } catch (SecurityException e) { mEdit.setText("Security Exception"); } catch (Exception e) { mEdit.setText(e.getMessage()); } break; case R.id.load: try { FileInputStream fis = new FileInputStream(mSdPath + "/dir/file.txt"); byte[] data = new byte[fis.available()]; while (fis.read(data) != -1) {; } fis.close(); mEdit.setText(new String(data)); } catch (FileNotFoundException e) { mEdit.setText("File Not Found"); } catch (Exception e) {; } break; } }
private void createFolders() { File file = null; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String settingDir = prefs.getString("dir_download", "0"); boolean writeLogFile = prefs.getBoolean("log_file_checkbox", false); if (settingDir.equals(Constants.EXTERNAL_STORAGE + "")) { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { file = new File(Environment.getExternalStorageDirectory() + Constants.DIRECTORY); boolean success = true; if (!file.exists()) { success = file.mkdirs(); } if (!success) file = null; } } if (file == null) file = new File(Environment.getRootDirectory() + Constants.DIRECTORY); if (!file.exists()) { if (!file.mkdirs()) { file = getDir("", MODE_WORLD_WRITEABLE); file = new File(file, Constants.DIRECTORY); if (!file.exists()) { file.mkdirs(); } } } File nomedia = new File(file, ".nomedia"); Helper.logFile = new File(file, Helper.LOG_FILE); Helper.writeLogFile = writeLogFile; try { nomedia.createNewFile(); } catch (IOException e) { Helper.logError(this, "Error creating .nomedia file.", e); } }
public static List<File> getImportFiles() { File extDir = Environment.getRootDirectory(); String state = Environment.getExternalStorageState(); // TODO check thru all state possibilities if (!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED)) { return new ArrayList<File>(); } ArrayList<File> fileList = new ArrayList<File>(); @SuppressWarnings("unchecked") Iterator<File> iter = FileUtils.iterateFiles(extDir, new String[] {"csv"}, true); while (iter.hasNext()) { File file = iter.next(); if (file.getName().startsWith("._")) { continue; } fileList.add(file); Log.d(LOG, "### disk Import File: " + file.getAbsolutePath()); } Log.i(LOG, "### Import Files in list : " + fileList.size()); return fileList; }
/** * Centralized access to SELinux MMAC (middleware MAC) implementation. This class is responsible for * loading the appropriate mac_permissions.xml file as well as providing an interface for assigning * seinfo values to apks. * * <p>{@hide} */ public final class SELinuxMMAC { static final String TAG = "SELinuxMMAC"; private static final boolean DEBUG_POLICY = false; private static final boolean DEBUG_POLICY_INSTALL = DEBUG_POLICY || false; private static final boolean DEBUG_POLICY_ORDER = DEBUG_POLICY || false; // All policy stanzas read from mac_permissions.xml. This is also the lock // to synchronize access during policy load and access attempts. private static List<Policy> sPolicies = new ArrayList<>(); /** Path to version on rootfs */ private static final File VERSION_FILE = new File("/selinux_version"); /** Path to MAC permissions on system image */ private static final File MAC_PERMISSIONS = new File(Environment.getRootDirectory(), "/etc/security/mac_permissions.xml"); /** Path to app contexts on rootfs */ private static final File SEAPP_CONTEXTS = new File("/seapp_contexts"); /** Calculated hash of {@link #SEAPP_CONTEXTS} */ private static final byte[] SEAPP_CONTEXTS_HASH = returnHash(SEAPP_CONTEXTS); /** Attribute where {@link #SEAPP_CONTEXTS_HASH} is stored */ private static final String XATTR_SEAPP_HASH = "user.seapp_hash"; // Append privapp to existing seinfo label private static final String PRIVILEGED_APP_STR = ":privapp"; // Append autoplay to existing seinfo label private static final String AUTOPLAY_APP_STR = ":autoplayapp"; /** * Load the mac_permissions.xml file containing all seinfo assignments used to label apps. The * loaded mac_permissions.xml file is determined by the MAC_PERMISSIONS class variable which is * set at class load time which itself is based on the USE_OVERRIDE_POLICY class variable. For * further guidance on the proper structure of a mac_permissions.xml file consult the source code * located at system/sepolicy/mac_permissions.xml. * * @return boolean indicating if policy was correctly loaded. A value of false typically indicates * a structural problem with the xml or incorrectly constructed policy stanzas. A value of * true means that all stanzas were loaded successfully; no partial loading is possible. */ public static boolean readInstallPolicy() { // Temp structure to hold the rules while we parse the xml file List<Policy> policies = new ArrayList<>(); FileReader policyFile = null; XmlPullParser parser = Xml.newPullParser(); try { policyFile = new FileReader(MAC_PERMISSIONS); Slog.d(TAG, "Using policy file " + MAC_PERMISSIONS); parser.setInput(policyFile); parser.nextTag(); parser.require(XmlPullParser.START_TAG, null, "policy"); while (parser.next() != XmlPullParser.END_TAG) { if (parser.getEventType() != XmlPullParser.START_TAG) { continue; } switch (parser.getName()) { case "signer": policies.add(readSignerOrThrow(parser)); break; default: skip(parser); } } } catch (IllegalStateException | IllegalArgumentException | XmlPullParserException ex) { StringBuilder sb = new StringBuilder("Exception @"); sb.append(parser.getPositionDescription()); sb.append(" while parsing "); sb.append(MAC_PERMISSIONS); sb.append(":"); sb.append(ex); Slog.w(TAG, sb.toString()); return false; } catch (IOException ioe) { Slog.w(TAG, "Exception parsing " + MAC_PERMISSIONS, ioe); return false; } finally { IoUtils.closeQuietly(policyFile); } // Now sort the policy stanzas PolicyComparator policySort = new PolicyComparator(); Collections.sort(policies, policySort); if (policySort.foundDuplicate()) { Slog.w(TAG, "ERROR! Duplicate entries found parsing " + MAC_PERMISSIONS); return false; } synchronized (sPolicies) { sPolicies = policies; if (DEBUG_POLICY_ORDER) { for (Policy policy : sPolicies) { Slog.d(TAG, "Policy: " + policy.toString()); } } } return true; } /** * Loop over a signer tag looking for seinfo, package and cert tags. A {@link Policy} instance * will be created and returned in the process. During the pass all other tag elements will be * skipped. * * @param parser an XmlPullParser object representing a signer element. * @return the constructed {@link Policy} instance * @throws IOException * @throws XmlPullParserException * @throws IllegalArgumentException if any of the validation checks fail while parsing tag values. * @throws IllegalStateException if any of the invariants fail when constructing the {@link * Policy} instance. */ private static Policy readSignerOrThrow(XmlPullParser parser) throws IOException, XmlPullParserException { parser.require(XmlPullParser.START_TAG, null, "signer"); Policy.PolicyBuilder pb = new Policy.PolicyBuilder(); // Check for a cert attached to the signer tag. We allow a signature // to appear as an attribute as well as those attached to cert tags. String cert = parser.getAttributeValue(null, "signature"); if (cert != null) { pb.addSignature(cert); } while (parser.next() != XmlPullParser.END_TAG) { if (parser.getEventType() != XmlPullParser.START_TAG) { continue; } String tagName = parser.getName(); if ("seinfo".equals(tagName)) { String seinfo = parser.getAttributeValue(null, "value"); pb.setGlobalSeinfoOrThrow(seinfo); readSeinfo(parser); } else if ("package".equals(tagName)) { readPackageOrThrow(parser, pb); } else if ("cert".equals(tagName)) { String sig = parser.getAttributeValue(null, "signature"); pb.addSignature(sig); readCert(parser); } else { skip(parser); } } return pb.build(); } /** * Loop over a package element looking for seinfo child tags. If found return the value attribute * of the seinfo tag, otherwise return null. All other tags encountered will be skipped. * * @param parser an XmlPullParser object representing a package element. * @param pb a Policy.PolicyBuilder instance to build * @throws IOException * @throws XmlPullParserException * @throws IllegalArgumentException if any of the validation checks fail while parsing tag values. * @throws IllegalStateException if there is a duplicate seinfo tag for the current package tag. */ private static void readPackageOrThrow(XmlPullParser parser, Policy.PolicyBuilder pb) throws IOException, XmlPullParserException { parser.require(XmlPullParser.START_TAG, null, "package"); String pkgName = parser.getAttributeValue(null, "name"); while (parser.next() != XmlPullParser.END_TAG) { if (parser.getEventType() != XmlPullParser.START_TAG) { continue; } String tagName = parser.getName(); if ("seinfo".equals(tagName)) { String seinfo = parser.getAttributeValue(null, "value"); pb.addInnerPackageMapOrThrow(pkgName, seinfo); readSeinfo(parser); } else { skip(parser); } } } private static void readCert(XmlPullParser parser) throws IOException, XmlPullParserException { parser.require(XmlPullParser.START_TAG, null, "cert"); parser.nextTag(); } private static void readSeinfo(XmlPullParser parser) throws IOException, XmlPullParserException { parser.require(XmlPullParser.START_TAG, null, "seinfo"); parser.nextTag(); } private static void skip(XmlPullParser p) throws IOException, XmlPullParserException { if (p.getEventType() != XmlPullParser.START_TAG) { throw new IllegalStateException(); } int depth = 1; while (depth != 0) { switch (p.next()) { case XmlPullParser.END_TAG: depth--; break; case XmlPullParser.START_TAG: depth++; break; } } } /** * Applies a security label to a package based on an seinfo tag taken from a matched policy. All * signature based policy stanzas are consulted and, if no match is found, the default seinfo * label of 'default' (set in ApplicationInfo object) is used. The security label is attached to * the ApplicationInfo instance of the package in the event that a matching policy was found. * * @param pkg object representing the package to be labeled. */ public static void assignSeinfoValue(PackageParser.Package pkg) { synchronized (sPolicies) { for (Policy policy : sPolicies) { String seinfo = policy.getMatchedSeinfo(pkg); if (seinfo != null) { pkg.applicationInfo.seinfo = seinfo; break; } } } if (pkg.applicationInfo.isAutoPlayApp()) pkg.applicationInfo.seinfo += AUTOPLAY_APP_STR; if (pkg.applicationInfo.isPrivilegedApp()) pkg.applicationInfo.seinfo += PRIVILEGED_APP_STR; if (DEBUG_POLICY_INSTALL) { Slog.i( TAG, "package (" + pkg.packageName + ") labeled with " + "seinfo=" + pkg.applicationInfo.seinfo); } } /** * Determines if a recursive restorecon on the given package data directory is needed. It does * this by comparing the SHA-1 of the seapp_contexts file against the stored hash in an xattr. * * <p>Note that the xattr isn't in the 'security' namespace, so this should only be run on * directories owned by the system. * * @return Returns true if the restorecon should occur or false otherwise. */ public static boolean isRestoreconNeeded(File file) { try { final byte[] buf = new byte[20]; final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SEAPP_HASH, buf); if ((len == 20) && Arrays.equals(SEAPP_CONTEXTS_HASH, buf)) { return false; } } catch (ErrnoException e) { if (e.errno != OsConstants.ENODATA) { Slog.e(TAG, "Failed to read seapp hash for " + file, e); } } return true; } /** * Stores the SHA-1 of the seapp_contexts into an xattr. * * <p>Note that the xattr isn't in the 'security' namespace, so this should only be run on * directories owned by the system. */ public static void setRestoreconDone(File file) { try { Os.setxattr(file.getAbsolutePath(), XATTR_SEAPP_HASH, SEAPP_CONTEXTS_HASH, 0); } catch (ErrnoException e) { Slog.e(TAG, "Failed to persist seapp hash in " + file, e); } } /** * Return the SHA-1 of a file. * * @param file The path to the file given as a string. * @return Returns the SHA-1 of the file as a byte array. */ private static byte[] returnHash(File file) { try { final byte[] contents = IoUtils.readFileAsByteArray(file.getAbsolutePath()); return MessageDigest.getInstance("SHA-1").digest(contents); } catch (IOException | NoSuchAlgorithmException e) { throw new RuntimeException(e); } } }
@Override protected Long doInBackground(String... params) { URL url; try { url = new URL(params[0]); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); // 当前线程下载的总大小 int total = 0; File positionFile = null; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { positionFile = new File(Environment.getExternalStorageDirectory(), getFileName(params[0]) + ".txt"); } else { positionFile = new File(Environment.getRootDirectory(), getFileName(params[0]) + ".txt"); } // 接着从上一次的位置继续下载数据 long startIndex = 0; if (positionFile.exists() && positionFile.length() > 0) { FileInputStream fis = new FileInputStream(positionFile); BufferedReader reader = new BufferedReader(new InputStreamReader(fis)); // 获取线程上次下载的总大小 String lastTotalstr = reader.readLine(); int lastTotal = Integer.parseInt(lastTotalstr); startIndex += lastTotal; total += lastTotal; // 加上上次下载的总大小。 fis.close(); } conn.setRequestProperty("Range", "bytes=" + startIndex + "-"); int responseCode = conn.getResponseCode(); long length = conn.getContentLength(); // 创建一个大小和服务器文件一样大小的文件 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { file = new File(Environment.getExternalStorageDirectory(), getFileName(params[0])); } else { file = new File(Environment.getRootDirectory(), getFileName(params[0])); } RandomAccessFile rcf = new RandomAccessFile(file, "rw"); rcf.setLength(length); long endIndex = length - 1; // 总大小 int threadSize = (int) (endIndex - startIndex); InputStream is = conn.getInputStream(); // 指定文件开始写的位置 rcf.seek(startIndex); int len = 0; byte[] buffer = new byte[1024]; int progress = 0; // 当前下载进度 while ((len = is.read(buffer)) != -1) { RandomAccessFile rf = new RandomAccessFile(positionFile, "rwd"); rcf.write(buffer, 0, len); total += len; rf.write(String.valueOf(total).getBytes()); rf.close(); progress = (int) ((total / (float) length) * 100); this.onProgressUpdate(progress); } is.close(); rcf.close(); System.out.println("下载完毕了"); return (long) progress; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 只有所有的线程都下载完毕后 才可以删除记录文件。 File f = null; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { file = new File(Environment.getExternalStorageDirectory(), getFileName(params[0])); } else { file = new File(Environment.getRootDirectory(), getFileName(params[0])); } f.delete(); } return null; }
/** * 图片选择,拍照,裁剪 * * @author E1230 */ public class PhotoPickUtil { private final int _2000 = 2000; private Activity activityContext; private Fragment fragmentContext; private OnPhotoPickedlistener onPhotoPickedlistener; /** * 普通的activity使用的构造器,回调activity中的onActivityResult(...) * * @param context * @param onPhotoPickedlistener */ public PhotoPickUtil(Activity context, OnPhotoPickedlistener onPhotoPickedlistener) { super(); this.activityContext = context; this.onPhotoPickedlistener = onPhotoPickedlistener; } /** * fragment使用的构造器,解决fragment中调用startActivityForResult时,没有回调fragment中的onActivityResult(...)而调用了Fragment管理activity的onActivityResult(...) * * @param activityContext * @param fragmentContext * @param onPhotoPickedlistener */ public PhotoPickUtil( Activity activityContext, Fragment fragmentContext, OnPhotoPickedlistener onPhotoPickedlistener) { super(); this.activityContext = activityContext; this.fragmentContext = fragmentContext; this.onPhotoPickedlistener = onPhotoPickedlistener; } /** 在调用的activity或fragment的onActivityResult(...)中调用次方法,处理拍照/相册返回的数据 */ public void pickResult(int requestCode, int resultCode, Intent data) { if (resultCode != Activity.RESULT_OK) return; switch (requestCode) { case CROPED_PHOTO: // 调用图片裁剪返回的 Bitmap img = data.getParcelableExtra("data"); if (onPhotoPickedlistener != null) { onPhotoPickedlistener.photoPicked(null, img); } break; case CAMERA_WITH_DATA: // 照相机程序返回的 // Toast.makeText(TApplication.getContext(),"拍照返回。。。。" + // mCurrentPhotoFile.getPath() + " -crop- " + doCrop,5000).show(); if (doCrop) { doCropPhoto(mCurrentPhotoFile, cropWidth, cropHeight); } else { if (onPhotoPickedlistener != null) { onPhotoPickedlistener.photoPicked(mCurrentPhotoFile.getPath(), null); mCurrentPhotoFile = null; } } break; case PHOTO_PICKED: // Bundle b = data.getExtras(); // for (Iterator<String> it = b.keySet().iterator();it.hasNext();){ // String key = it.next(); // LogUtil.info("附加值 - " + key + " - " + b.get(key)); // } Uri originalUri = data.getData(); // 调用相册选择返回的图片 String path = getGalleryImgPath(originalUri); // Toast.makeText(TApplication.getContext(),"相册返回。。。。" + path,5000).show(); if (TextUtils.isEmpty(path)) { return; } if (doCrop) { doCropPhoto(new File(path), cropWidth, cropHeight); } else { if (onPhotoPickedlistener != null) { onPhotoPickedlistener.photoPicked(path, null); } } break; } } /** 是否裁剪 */ private boolean doCrop; /** 裁剪宽度 */ private int cropWidth; /** 裁剪高度 */ private int cropHeight; /* * 用来标识请求照相功能的 activity */ public final int CAMERA_WITH_DATA = 3023; /* * 用来标识请求 gallery 的 activity */ public final int CAMERA_CROP = 3022; /* * 用来标识请求 gallery 的 activity */ public final int CROPED_PHOTO = 3021; public final int PHOTO_PICKED = 3024; /* * 拍照的照片存储位置 */ private final File PHOTO_DIR_SD = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera"); private final File PHOTO_DIR_ROOT = new File(Environment.getRootDirectory() + "/DCIM/Camera"); private File mCurrentPhotoFile; // 照相机拍照得到的图片 /** * 有取消选择的图片(需设置监听器),拍照和选择图片3个选项 * * @param activity * @param cropImg * @param outWith * @param outHeight * @param cancelClickListener */ public void doPickPhotoAction( final boolean cropImg, final int outWith, final int outHeight, final OnPickPhotoCancelClickListener cancelClickListener) { this.doCrop = cropImg; this.cropWidth = outWith; this.cropHeight = outHeight; File dir = null; // showToast(activity, "若添加实时拍摄照片导致重启,请尝试在应用外拍照,再选择从相册中获取进行添加!"); String status = Environment.getExternalStorageState(); if (status.equals(Environment.MEDIA_MOUNTED)) { // 判断是否有SD卡 dir = PHOTO_DIR_SD; } else { dir = PHOTO_DIR_ROOT; } if (!dir.exists()) { dir.mkdirs(); // 创建照片的存储目录 } mCurrentPhotoFile = new File(dir, getImgName()); // 给新照的照片文件命名 // Wrap our context to inflate list items using correct theme Context dialogContext = new ContextThemeWrapper(activityContext, android.R.style.Theme_Light); String cancel = "返回"; String[] choices = new String[3]; choices[0] = "清除"; // choices[1] = "拍照"; // getString(MediaStore.ACTION_IMAGE_CAPTURE); //拍照 choices[2] = "从相册选择图片"; // getString(R.string.pick_photo); //从相册中选择 ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext); builder.setTitle("选择图片"); builder.setSingleChoiceItems( adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); switch (which) { case 0: if (cancelClickListener != null) { cancelClickListener.onClick(); } dialog.dismiss(); break; case 1: { doTakePhoto(); break; } case 2: doPickPhotoFromGallery(); // 从相册中去获取 break; } } }); builder.setNegativeButton( cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } /** * 只有拍照和选择照片两个选项 * * @param activity * @param cropImg * @param outWith * @param outHeight */ public void doPickPhotoAction(final boolean cropImg, final int outWith, final int outHeight) { this.doCrop = cropImg; this.cropWidth = outWith; this.cropHeight = outHeight; File dir = null; // showToast(activity, "若添加实时拍摄照片导致重启,请尝试在应用外拍照,再选择从相册中获取进行添加!"); String status = Environment.getExternalStorageState(); if (status.equals(Environment.MEDIA_MOUNTED)) { // 判断是否有SD卡 dir = PHOTO_DIR_SD; } else { dir = PHOTO_DIR_ROOT; } if (!dir.exists()) { dir.mkdirs(); // 创建照片的存储目录 } mCurrentPhotoFile = new File(dir, getImgName()); // 给新照的照片文件命名 // Wrap our context to inflate list items using correct theme Context dialogContext = new ContextThemeWrapper(activityContext, android.R.style.Theme_Light); String cancel = "返回"; String[] choices = new String[2]; choices[0] = "拍照"; // getString(MediaStore.ACTION_IMAGE_CAPTURE); //拍照 choices[1] = "从相册选择图片"; // getString(R.string.pick_photo); //从相册中选择 ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext); builder.setTitle("选择图片"); builder.setSingleChoiceItems( adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); switch (which) { case 0: { doTakePhoto(); break; } case 1: doPickPhotoFromGallery(); // 从相册中去获取 break; } } }); builder.setNegativeButton( cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } /** * 直接调用系统拍照,用于自定义界面 * * @param cropImg * @param outWith * @param outHeight */ public void takePhoto(final boolean cropImg, final int outWith, final int outHeight) { this.doCrop = cropImg; this.cropWidth = outWith; this.cropHeight = outHeight; File dir = null; // showToast(activity, "若添加实时拍摄照片导致重启,请尝试在应用外拍照,再选择从相册中获取进行添加!"); String status = Environment.getExternalStorageState(); if (status.equals(Environment.MEDIA_MOUNTED)) { // 判断是否有SD卡 dir = PHOTO_DIR_SD; } else { dir = PHOTO_DIR_ROOT; } if (!dir.exists()) { dir.mkdirs(); // 创建照片的存储目录 } mCurrentPhotoFile = new File(dir, getImgName()); // 给新照的照片文件命名 doTakePhoto(); } /** * 直接调用系统相册获取图片,用于自定义界面 * * @param cropImg * @param outWith * @param outHeight */ public void chooseFromGallery(final boolean cropImg, final int outWith, final int outHeight) { this.doCrop = cropImg; this.cropWidth = outWith; this.cropHeight = outHeight; doPickPhotoFromGallery(); // 从相册中去获取 } /** * 拍照获取图片 * * @param cropImg */ private void doTakePhoto() { try { final Intent intent = getTakePickIntent(mCurrentPhotoFile); if (fragmentContext != null) fragmentContext.startActivityForResult(intent, CAMERA_WITH_DATA); else activityContext.startActivityForResult(intent, CAMERA_WITH_DATA); } catch (ActivityNotFoundException e) { e.printStackTrace(); Toast.makeText(activityContext, "图片获取失败", _2000).show(); } } private Intent getTakePickIntent(File f) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)); if (doCrop) { intent.putExtra("return-data", true); } return intent; } // 请求Gallery程序 private void doPickPhotoFromGallery() { try { // Launch picker to choose photo for selected contact final Intent intent = getPhotoPickIntent(); if (fragmentContext != null) fragmentContext.startActivityForResult(intent, PHOTO_PICKED); else activityContext.startActivityForResult(intent, PHOTO_PICKED); } catch (ActivityNotFoundException e) { e.printStackTrace(); Toast.makeText(activityContext, "图片获取失败", _2000).show(); } } // 封装请求Gallery的intent private Intent getPhotoPickIntent() { Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); // Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null); // intent.setType("image/*"); // if (cropImg) { // intent.putExtra("crop", "true"); // // 设置裁剪框高宽比例和输出的图片尺寸,不设为原始尺寸 // // if (outHeight > outWith) { // // intent.putExtra("aspectX", 1); // // intent.putExtra("aspectY", outHeight / outWith); // // } else if (outWith > outHeight) { // intent.putExtra("aspectX", outWith); // intent.putExtra("aspectY", outHeight); // // } // intent.putExtra("outputX", outWith); // intent.putExtra("outputY", outHeight); // // 设置使系统返回图片bitmap对象 // intent.putExtra("return-data", true); // } return intent; } private void doCropPhoto(File f, int outWith, int outHeight) { try { // 启动gallery去剪辑这个照片 final Intent intent = getCropImageIntent(Uri.fromFile(f), outWith, outHeight); if (fragmentContext != null) fragmentContext.startActivityForResult(intent, CROPED_PHOTO); else activityContext.startActivityForResult(intent, CROPED_PHOTO); } catch (Exception e) { Toast.makeText(activityContext, "图片获取失败", _2000).show(); } } /** Constructs an intent for image cropping. 调用图片剪辑程序 */ private Intent getCropImageIntent(Uri photoUri, int outWith, int outHeight) { Intent intent = new Intent("com.android.camera.action.CROP") .setDataAndType(photoUri, "image/*") .putExtra("crop", "true") .putExtra("return-data", true); // .putExtra("scale", true) // // 黑边 // .putExtra("scaleUpIfNeeded", true) // // 黑边 intent.putExtra("aspectX", outWith); intent.putExtra("aspectY", outHeight); intent.putExtra("outputX", outWith); intent.putExtra("outputY", outHeight); return intent; } @SuppressWarnings("deprecation") private String getGalleryImgPath(Uri photoUri) { // 这里开始的第二部分,获取图片的路径: String[] proj = {MediaStore.Images.Media.DATA}; // 好像是android多媒体数据库的封装接口,具体的看Android文档 Cursor cursor = activityContext.managedQuery(photoUri, proj, null, null, null); // 按我个人理解 这个是获得用户选择的图片的索引值 int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); // 将光标移至开头 ,这个很重要,不小心很容易引起越界 cursor.moveToFirst(); // 最后根据索引值获取图片路径 String path = cursor.getString(column_index); return path; } public static String getImgName() { // SimpleDateFormat sdf = new SimpleDateFormat(); // sdf.applyPattern("yyyyMMdd_HHmmsss"); StringBuilder result = new StringBuilder("IMG_"); result .append( DateFormat.format("yyyyMMdd_HHmmsss", new Date()).toString() + (int) (Math.random() * 100)) .append(".jpg"); return result.toString(); } public interface OnPhotoPickedlistener { /** * 调用返回,若为拍照或从图库中直接读取,path有值,bmp为null,若经过裁剪,path为null,bmp有值 * * @param path * @param bmp */ public void photoPicked(String path, Bitmap bmp); } public interface OnPickPhotoCancelClickListener { public void onClick(); } /** * 将图片信息插入系统数据库,在系统相册中便能看到这个图片 * * @param context * @param title * @param name * @param path * @param mimeType */ public static void insertMedia( Context context, String title, String name, String path, String mimeType) { ContentValues values = new ContentValues(7); values.put(MediaStore.Images.Media.TITLE, title); values.put(MediaStore.Images.Media.DISPLAY_NAME, name); values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis()); values.put(MediaStore.Images.Media.MIME_TYPE, mimeType); // "image/jpeg" values.put(MediaStore.Images.Media.DATA, path); context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } }
public long FreeMemory() { StatFs statFs = new StatFs(Environment.getRootDirectory().getAbsolutePath()); long Free = (statFs.getAvailableBlocks() * statFs.getBlockSize()) / MB; return Free; }
public long TotalMemory() { StatFs statFs = new StatFs(Environment.getRootDirectory().getAbsolutePath()); long Total = (statFs.getBlockCount() * statFs.getBlockSize()) / MB; return Total; }
/** * 获取系统存储路径 * * @return */ public static String getRootDirectoryPath() { return Environment.getRootDirectory().getAbsolutePath(); }
private String getDeviceInfos() throws IllegalAccessException, IllegalArgumentException { if (_deviceInfos != null) { return _deviceInfos; } String result = "<table>"; List<Field> list = new ArrayList<Field>(); list.addAll(Arrays.asList(android.os.Build.VERSION.class.getDeclaredFields())); list.addAll(Arrays.asList(android.os.Build.class.getDeclaredFields())); for (Field field : list) { field.setAccessible(true); try { result += "<tr><td>" + field.getDeclaringClass().toString().substring(6).replace("$", ".") + "." + field.getName() + "</td><td>" + field.get(null).toString() + "</td></tr>\n"; } catch (IllegalAccessException e1) { } catch (IllegalArgumentException e1) { } } for (Entry<Object, Object> e : System.getProperties().entrySet()) { result += "<tr><td>Property: " + e.getKey() + "</td><td>" + e.getValue() + "</td></tr>\n"; } result += "<tr><td>Environment: getDataDirectory()</td><td>" + Environment.getDataDirectory() + "</td></tr>\n"; result += "<tr><td>Environment: getDownloadCacheDirectory()</td><td>" + Environment.getDownloadCacheDirectory() + "</td></tr>\n"; result += "<tr><td>Environment: getExternalStorageDirectory()" + "</td><td>" + Environment.getExternalStorageDirectory() + "</td></tr>\n"; result += "<tr><td>Environment: getExternalStoragePublicDirectory(DIRECTORY_ALARMS)</td><td>" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_ALARMS) + "</td></tr>\n"; result += "<tr><td>Environment: getExternalStoragePublicDirectory(DIRECTORY_DCIM)</td><td>" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "</td></tr>\n"; result += "<tr><td>Environment: getExternalStoragePublicDirectory(DIRECTORY_DOWNLOAD)</td><td>" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "</td></tr>\n"; result += "<tr><td>Environment: getExternalStoragePublicDirectory(DIRECTORY_MOVIES)</td><td>" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) + "</td></tr>\n"; result += "<tr><td>Environment: getExternalStoragePublicDirectory(DIRECTORY_MUSIC)</td><td>" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) + "</td></tr>\n"; result += "<tr><td>Environment: getExternalStoragePublicDirectory(DIRECTORY_NOTIFICATIONS)</td><td>" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_NOTIFICATIONS) + "</td></tr>\n"; result += "<tr><td>Environment: getExternalStoragePublicDirectory(DIRECTORY_PICTURES)</td><td>" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "</td></tr>\n"; result += "<tr><td>Environment: getExternalStoragePublicDirectory(DIRECTORY_PODCASTS)</td><td>" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PODCASTS) + "</td></tr>\n"; result += "<tr><td>Environment: getExternalStoragePublicDirectory(DIRECTORY_RINGTONES)</td><td>" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES) + "</td></tr>\n"; result += "<tr><td>Environment: getRootDirectory()</td><td>" + Environment.getRootDirectory() + "</td></tr>\n"; result += "<tr><td>Context: getPackageResourcePath()</td><td>" + _context.getPackageResourcePath() + "</td></tr>\n"; result += "<tr><td>Context: getCacheDir()</td><td>" + _context.getCacheDir() + "</td></tr>\n"; result += "<tr><td>Context: getExternalCacheDir()</td><td>" + _context.getExternalCacheDir() + "</td></tr>\n"; result += "<tr><td>Context: getExternalFilesDir(DIRECTORY_ALARMS)</td><td>" + _context.getExternalFilesDir(Environment.DIRECTORY_ALARMS) + "</td></tr>\n"; result += "<tr><td>Context: getExternalFilesDir(DIRECTORY_DCIM)</td><td>" + _context.getExternalFilesDir(Environment.DIRECTORY_DCIM) + "</td></tr>\n"; result += "<tr><td>Context: getExternalFilesDir(DIRECTORY_DOWNLOADS)</td><td>" + _context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "</td></tr>\n"; result += "<tr><td>Context: getExternalFilesDir(DIRECTORY_MOVIES)</td><td>" + _context.getExternalFilesDir(Environment.DIRECTORY_MOVIES) + "</td></tr>\n"; result += "<tr><td>Context: getExternalFilesDir(DIRECTORY_MUSIC)</td><td>" + _context.getExternalFilesDir(Environment.DIRECTORY_MUSIC) + "</td></tr>\n"; result += "<tr><td>Context: getExternalFilesDir(DIRECTORY_NOTIFICATIONS)</td><td>" + _context.getExternalFilesDir(Environment.DIRECTORY_NOTIFICATIONS) + "</td></tr>\n"; result += "<tr><td>Context: getExternalFilesDir(DIRECTORY_PICTURES)</td><td>" + _context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "</td></tr>\n"; result += "<tr><td>Context: getExternalFilesDir(DIRECTORY_PODCASTS)</td><td>" + _context.getExternalFilesDir(Environment.DIRECTORY_PODCASTS) + "</td></tr>\n"; result += "<tr><td>Context: getExternalFilesDir(DIRECTORY_RINGTONES)</td><td>" + _context.getExternalFilesDir(Environment.DIRECTORY_RINGTONES) + "</td></tr>\n"; result += "<tr><td>Context: getFilesDir()</td><td>" + _context.getFilesDir() + "</td></tr>\n"; { for (Class<?> subclass : ContactsContract.CommonDataKinds.class.getDeclaredClasses()) { Log.d(AppConfig.TAG_APP, TAG + "getDeviceInfos: looking at " + subclass.getName()); if (subclass != null) { Method m = null; for (Method mm : subclass.getDeclaredMethods()) { if (mm.getName().equals("getTypeLabelResource") || mm.getName().equals("getTypeResource")) { m = mm; break; } } if (m != null) { for (Field field : subclass.getDeclaredFields()) { if (field.getName().startsWith("TYPE_")) { Object obj = field.get(null); if (obj instanceof Integer) { try { int type = (Integer) obj; int res = (Integer) m.invoke(null, type); result += "<tr><td>ContactsContract.CommonDataKinds." + field.getDeclaringClass().getSimpleName() + "." + field.getName() + "</td><td>" + _context.getString(res) + "</td></tr>\n"; } catch (InvocationTargetException e1) { Log.e(AppConfig.TAG_APP, TAG + "getDeviceInfos: error", e1); } } } } } } } } result += "</table>"; _deviceInfos = result; return result; }
protected final void DV() { boolean bool2 = true; Object localObject2 = null; hdM = ((ListView)findViewById(a.i.qqmail_file_explorer_list_lv)); hdO = ((TextView)findViewById(a.i.root_tab)); hdQ = findViewById(a.i.root_tab_selector); hdP = ((TextView)findViewById(a.i.sdcard_tab)); hdR = findViewById(a.i.sdcard_tab_selector); a(new k(this)); hdS = getString(a.n.plugin_qqmail_file_explorer_root_tag); hdT = getString(a.n.plugin_qqmail_file_explorer_sdcard_tag); File localFile1; label126: File localFile2; label140: Object localObject1; if (bn.iW(bisbhN)) { localFile1 = Environment.getRootDirectory(); if (!localFile1.canRead()) { break label470; } if (!ax.tl().isSDCardAvailable()) { break label497; } localFile2 = com.tencent.mm.compatible.util.j.getExternalStorageDirectory(); h localh = ax.tl().rf(); if (localFile1 != null) { break label558; } localObject1 = null; label155: localObject1 = (String)localh.get(131073, localObject1); if ((localObject1 == null) || (localFile1 == null) || (localFile1.getAbsolutePath().equals(localObject1))) { break label567; } localObject1 = new File((String)localObject1); if (!((File)localObject1).exists()) { break label567; } label210: hdU = ((File)localObject1); localh = ax.tl().rf(); if (localFile2 != null) { break label573; } localObject1 = localObject2; label233: localObject1 = (String)localh.get(131074, localObject1); if ((localObject1 == null) || (localFile2 == null) || (localFile2.getAbsolutePath().equals(localObject1))) { break label583; } localObject1 = new File((String)localObject1); if (!((File)localObject1).exists()) { break label583; } label290: hdV = ((File)localObject1); hdN = new a((byte)0); if (localFile2 == null) { break label590; } lS(1); hdN.fqn = localFile2.getPath(); hdN.a(hdV.getParentFile(), hdV); label349: localObject1 = hdO; if (localFile1 == null) { break label641; } bool1 = true; label361: ((TextView)localObject1).setEnabled(bool1); localObject1 = hdP; if (localFile2 == null) { break label646; } } label470: label497: label552: label558: label567: label573: label583: label590: label641: label646: for (boolean bool1 = bool2;; bool1 = false) { ((TextView)localObject1).setEnabled(bool1); hdM.setAdapter(hdN); hdN.notifyDataSetChanged(); hdM.setOnItemClickListener(new l(this)); hdO.setOnClickListener(new m(this, localFile1)); hdP.setOnClickListener(new n(this, localFile2)); return; localFile1 = new File(bisbhN); break; localFile1 = com.tencent.mm.compatible.util.j.getDataDirectory(); if (localFile1.canRead()) { hdS = localFile1.getName(); break label126; } localFile1 = null; break label126; if (bn.iW(bisbhP)) {} for (localFile2 = Environment.getDownloadCacheDirectory();; localFile2 = new File(bisbhP)) { if (!localFile2.canRead()) { break label552; } hdT = localFile2.getName(); break; } localFile2 = null; break label140; localObject1 = localFile1.getAbsolutePath(); break label155; localObject1 = localFile1; break label210; localObject1 = localFile2.getAbsolutePath(); break label233; localObject1 = localFile2; break label290; if (localFile1 != null) { lS(0); hdN.fqn = localFile1.getPath(); hdN.a(hdU.getParentFile(), hdU); break label349; } t.d("!32@/B4Tb64lLpKKG/WupdUGi6Sns9bhKpSP", "left and right tag disabled in the same time."); return; bool1 = false; break label361; } }