android.os.Environment#getDataDirectory ( )源码实例Demo

下面列出了android.os.Environment#getDataDirectory ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: TestChat   文件: CommonImageLoader.java
public File takePhoto(Activity activity, int requestCodeTakePicture) {

                File dir;
                if (FileUtil.isExistSDCard()) {
                        dir = FileUtil.newDir(Constant.IMAGE_CACHE_DIR + "take_picture/");
                } else {
                        dir = Environment.getDataDirectory();
                }
                File file=null;
                if (dir != null) {
                        file = FileUtil.newFile(dir.getAbsolutePath() + System.currentTimeMillis() + ".jpg");
                }
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                activity.startActivityForResult(intent, requestCodeTakePicture);
                return file;

        }
 
源代码2 项目: AndroidStudyDemo   文件: DatabaseExportUtil.java
/**
 * 开始导出数据 此操作比较耗时,建议在线程中进行
 * @param context      上下文
 * @param targetFile   目标文件
 * @param databaseName 要拷贝的数据库文件名
 * @return 是否倒出成功
 */
public boolean startExportDatabase(Context context, String targetFile,
                                   String databaseName) {
    Logger.d("start export ...");
    if (!Environment.MEDIA_MOUNTED.equals(Environment
            .getExternalStorageState())) {
        Logger.d("cannot find SDCard");
        return false;
    }
    String sourceFilePath = Environment.getDataDirectory() + "/data/"
            + context.getPackageName() + "/databases/" + databaseName;
    String destFilePath = Environment.getExternalStorageDirectory()
            + (TextUtils.isEmpty(targetFile) ? (context.getPackageName() + ".db")
            : targetFile);
    boolean isCopySuccess = FileUtil
            .copyFile(sourceFilePath, destFilePath);
    if (isCopySuccess) {
        Logger.d("copy database file success. target file : "
                + destFilePath);
    } else {
        Logger.d("copy database file failure");
    }
    return isCopySuccess;
}
 
源代码3 项目: tinker-manager   文件: SampleUtils.java
@Deprecated
public static boolean checkRomSpaceEnough(long limitSize) {
    long allSize;
    long availableSize = 0;
    try {
        File data = Environment.getDataDirectory();
        StatFs sf = new StatFs(data.getPath());
        availableSize = (long) sf.getAvailableBlocks() * (long) sf.getBlockSize();
        allSize = (long) sf.getBlockCount() * (long) sf.getBlockSize();
    } catch (Exception e) {
        allSize = 0;
    }

    if (allSize != 0 && availableSize > limitSize) {
        return true;
    }
    return false;
}
 
源代码4 项目: kcanotify   文件: KcaPacketLogger.java
public boolean dump(Context context){
    File savedir = new File(context.getExternalFilesDir(null).getAbsolutePath().concat(LOG_PATH));
    if (!savedir.exists()) savedir.mkdirs();
    String exportPath = savedir.getPath();

    File data = Environment.getDataDirectory();
    FileChannel source, destination;
    String currentDBPath = "/data/"+ BuildConfig.APPLICATION_ID +"/databases/" + packetlog_db_name;
    String backupDBPath = packetlog_db_name;
    File currentDB = new File(data, currentDBPath);
    File backupDB = new File(exportPath, backupDBPath);
    try {
        source = new FileInputStream(currentDB).getChannel();
        destination = new FileOutputStream(backupDB).getChannel();
        destination.transferFrom(source, 0, source.size());
        source.close();
        destination.close();
        return true;
    } catch(IOException e) {
        e.printStackTrace();
        return false;
    }
}
 
源代码5 项目: fresco   文件: StatFsHelper.java
/** Initialization code that can sometimes take a long time. */
private void ensureInitialized() {
  if (!mInitialized) {
    lock.lock();
    try {
      if (!mInitialized) {
        mInternalPath = Environment.getDataDirectory();
        mExternalPath = Environment.getExternalStorageDirectory();
        updateStats();
        mInitialized = true;
      }
    } finally {
      lock.unlock();
    }
  }
}
 
源代码6 项目: MyUtil   文件: DeviceUtils.java
/**
 * 获取手机内部总存储空间 单位byte
 * @return
 */
@SuppressWarnings("deprecation")
public static long getTotalInternalStorageSize() {
    File path = Environment.getDataDirectory();
    StatFs stat = new StatFs(path.getPath());

    if(Build.VERSION.SDK_INT >= 18) {
        return stat.getTotalBytes();
    } else {
        return (long) stat.getBlockCount() * stat.getBlockSize();
    }
}
 
源代码7 项目: GoogleFitExample   文件: MainActivity.java
/**
 * Used for debugging to restore some meaningful data
 */
public void restoreDatabase() {
    boolean hasPermission = (ContextCompat.checkSelfPermission(this,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
    if (!hasPermission) {
        ActivityCompat.requestPermissions(this,
                new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
                REQUEST_WRITE_STORAGE);
    }
    Log.d("MainActivity", "Restoring database.");
    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            String backupDBPath = "//data//com.blackcj.fitdata//databases//googlefitexample.db";
            String currentDBPath = "sdcard/backup.db";
            File currentDB = new File(currentDBPath);
            File backupDB = new File(data, backupDBPath);

            if (currentDB.exists()) {
                FileChannel src = new FileInputStream(currentDB).getChannel();
                FileChannel dst = new FileOutputStream(backupDB).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
                Log.d("MainActivity", "Database restored.");
            } else {
                Log.d("MainActivity", "Database doesn't exist.");
            }
        }else {
            Log.d("MainActivity", "Unable to write file.");
        }
    } catch (Exception e) {
        Log.d("MainActivity", "Exception restoring database");
    }
}
 
源代码8 项目: HeroVideo-master   文件: CommonUtil.java
/**
 * 获取手机内存存储可用空间
 *
 * @return
 */
public static long getPhoneAvailableSize()
{

    if (!checkSdCard())
    {
        File path = Environment.getDataDirectory();
        StatFs mStatFs = new StatFs(path.getPath());
        long blockSizeLong = mStatFs.getBlockSizeLong();
        long availableBlocksLong = mStatFs.getAvailableBlocksLong();
        return blockSizeLong * availableBlocksLong;
    } else
        return getSDcardAvailableSize();
}
 
源代码9 项目: android_9.0.0_r45   文件: GraphicsStatsService.java
public GraphicsStatsService(Context context) {
    mContext = context;
    mAppOps = context.getSystemService(AppOpsManager.class);
    mAlarmManager = context.getSystemService(AlarmManager.class);
    File systemDataDir = new File(Environment.getDataDirectory(), "system");
    mGraphicsStatsDir = new File(systemDataDir, "graphicsstats");
    mGraphicsStatsDir.mkdirs();
    if (!mGraphicsStatsDir.exists()) {
        throw new IllegalStateException("Graphics stats directory does not exist: "
                + mGraphicsStatsDir.getAbsolutePath());
    }
    HandlerThread bgthread = new HandlerThread("GraphicsStats-disk", Process.THREAD_PRIORITY_BACKGROUND);
    bgthread.start();

    mWriteOutHandler = new Handler(bgthread.getLooper(), new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case SAVE_BUFFER:
                    saveBuffer((HistoricalBuffer) msg.obj);
                    break;
                case DELETE_OLD:
                    deleteOldBuffers();
                    break;
            }
            return true;
        }
    });
}
 
源代码10 项目: stynico   文件: FxService.java
private String getRomAvailableSize()
{
    File path = Environment.getDataDirectory();
    StatFs stat = new StatFs(path.getPath());
    long blockSize = stat.getBlockSize();
    long availableBlocks = stat.getAvailableBlocks();
    return Formatter.formatFileSize(this, blockSize * availableBlocks);
}
 
源代码11 项目: WaniKani-for-Android   文件: PrefManager.java
public static void logout(Context context) {
    prefs.edit().clear().commit();
    reviewsPrefs.edit().clear().commit();

    File offlineData = new File(Environment.getDataDirectory() + "/data/" + context.getPackageName() + "/shared_prefs/offline_data.xml");
    File cacheDir = new File(Environment.getDataDirectory() + "/data/" + context.getPackageName() + "/cache");
    File webviewCacheDir = new File(Environment.getDataDirectory() + "/data/" + context.getPackageName() + "/app_webview");

    try {
        if (offlineData.exists()) {
            offlineData.delete();
        }
        FileUtils.deleteDirectory(cacheDir);
        FileUtils.deleteDirectory(webviewCacheDir);
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Cancel the notification alarm...
    Intent notificationIntent = new Intent(context, NotificationPublisher.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(
            context,
            NotificationPublisher.REQUEST_CODE,
            notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT
    );
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(pendingIntent);
}
 
源代码12 项目: AutoCrashReporter   文件: AutoErrorReporter.java
private long getAvailableInternalMemorySize() {
	File path = Environment.getDataDirectory();
	StatFs stat = new StatFs(path.getPath());
	long blockSize = stat.getBlockSize();
	long availableBlocks = stat.getAvailableBlocks();
	return (availableBlocks * blockSize)/(1024*1024);
}
 
源代码13 项目: android_9.0.0_r45   文件: StorageManagerService.java
/**
 * Constructs a new StorageManagerService instance
 *
 * @param context  Binder context for this service
 */
public StorageManagerService(Context context) {
    sSelf = this;

    mContext = context;
    mCallbacks = new Callbacks(FgThread.get().getLooper());
    mLockPatternUtils = new LockPatternUtils(mContext);

    // XXX: This will go away soon in favor of IMountServiceObserver
    mPms = (PackageManagerService) ServiceManager.getService("package");

    HandlerThread hthread = new HandlerThread(TAG);
    hthread.start();
    mHandler = new StorageManagerServiceHandler(hthread.getLooper());

    // Add OBB Action Handler to StorageManagerService thread.
    mObbActionHandler = new ObbActionHandler(IoThread.get().getLooper());

    // Initialize the last-fstrim tracking if necessary
    File dataDir = Environment.getDataDirectory();
    File systemDir = new File(dataDir, "system");
    mLastMaintenanceFile = new File(systemDir, LAST_FSTRIM_FILE);
    if (!mLastMaintenanceFile.exists()) {
        // Not setting mLastMaintenance here means that we will force an
        // fstrim during reboot following the OTA that installs this code.
        try {
            (new FileOutputStream(mLastMaintenanceFile)).close();
        } catch (IOException e) {
            Slog.e(TAG, "Unable to create fstrim record " + mLastMaintenanceFile.getPath());
        }
    } else {
        mLastMaintenance = mLastMaintenanceFile.lastModified();
    }

    mSettingsFile = new AtomicFile(
            new File(Environment.getDataSystemDirectory(), "storage.xml"), "storage-settings");

    synchronized (mLock) {
        readSettingsLocked();
    }

    LocalServices.addService(StorageManagerInternal.class, mStorageManagerInternal);

    final IntentFilter userFilter = new IntentFilter();
    userFilter.addAction(Intent.ACTION_USER_ADDED);
    userFilter.addAction(Intent.ACTION_USER_REMOVED);
    mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);

    synchronized (mLock) {
        addInternalVolumeLocked();
    }

    // Add ourself to the Watchdog monitors if enabled.
    if (WATCHDOG_ENABLE) {
        Watchdog.getInstance().addMonitor(this);
    }
}
 
源代码14 项目: xposed-art   文件: XSharedPreferences.java
public XSharedPreferences(String packageName, String prefFileName) {
	mFile = new File(Environment.getDataDirectory(), "data/" + packageName + "/shared_prefs/" + prefFileName + ".xml");
	startLoadFromDisk();
}
 
源代码15 项目: android_9.0.0_r45   文件: AbstractStatsBase.java
protected AtomicFile getFile() {
    File dataDir = Environment.getDataDirectory();
    File systemDir = new File(dataDir, "system");
    File fname = new File(systemDir, mFileName);
    return new AtomicFile(fname);
}
 
private static File getSettingsProblemFile() {
    File dataDir = Environment.getDataDirectory();
    File systemDir = new File(dataDir, "system");
    File fname = new File(systemDir, "uiderrors.txt");
    return fname;
}
 
源代码17 项目: product-emm   文件: DeviceStateJB.java
public DeviceStateJB(Context context) {
	this.context = context;
	this.info = new DeviceInfo(context);
	this.dataDirectory = Environment.getDataDirectory();
	this.directoryStatus = new StatFs(dataDirectory.getPath());
}
 
源代码18 项目: DevUtils   文件: PathUtils.java
/**
 * 获取 data 目录 - path /data
 * @return /system
 */
public File getDataDirectory() {
    return Environment.getDataDirectory();
}
 
源代码19 项目: android_9.0.0_r45   文件: UserManagerService.java
/**
 * Called by package manager to create the service.  This is closely
 * associated with the package manager, and the given lock is the
 * package manager's own lock.
 */
UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
        Object packagesLock) {
    this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
}
 
源代码20 项目: MobileGuard   文件: AppManagerEngine.java
/**
 * get the rom free space
 *
 * @return the byte of free space
 */
public static long getRomFreeSpace() {
    File directory = Environment.getDataDirectory();
    return directory.getFreeSpace();
}