Java Code Examples for android.os.Environment#getDataDirectory()

The following examples show how to use android.os.Environment#getDataDirectory() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CommonImageLoader.java    From TestChat with Apache License 2.0 6 votes vote down vote up
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;

        }
 
Example 2
Source File: StatFsHelper.java    From fresco with MIT License 6 votes vote down vote up
/** 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();
    }
  }
}
 
Example 3
Source File: DatabaseExportUtil.java    From AndroidStudyDemo with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 开始导出数据 此操作比较耗时,建议在线程中进行
 * @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;
}
 
Example 4
Source File: SampleUtils.java    From tinker-manager with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 5
Source File: KcaPacketLogger.java    From kcanotify with GNU General Public License v3.0 6 votes vote down vote up
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;
    }
}
 
Example 6
Source File: DeviceUtils.java    From MyUtil with Apache License 2.0 5 votes vote down vote up
/**
 * 获取手机内部总存储空间 单位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();
    }
}
 
Example 7
Source File: MainActivity.java    From GoogleFitExample with Apache License 2.0 5 votes vote down vote up
/**
 * 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");
    }
}
 
Example 8
Source File: CommonUtil.java    From HeroVideo-master with Apache License 2.0 5 votes vote down vote up
/**
 * 获取手机内存存储可用空间
 *
 * @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();
}
 
Example 9
Source File: GraphicsStatsService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
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;
        }
    });
}
 
Example 10
Source File: FxService.java    From stynico with MIT License 5 votes vote down vote up
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);
}
 
Example 11
Source File: AutoErrorReporter.java    From AutoCrashReporter with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 12
Source File: PrefManager.java    From WaniKani-for-Android with GNU General Public License v3.0 5 votes vote down vote up
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);
}
 
Example 13
Source File: StorageManagerService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
/**
 * 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);
    }
}
 
Example 14
Source File: DeviceStateJB.java    From product-emm with Apache License 2.0 4 votes vote down vote up
public DeviceStateJB(Context context) {
	this.context = context;
	this.info = new DeviceInfo(context);
	this.dataDirectory = Environment.getDataDirectory();
	this.directoryStatus = new StatFs(dataDirectory.getPath());
}
 
Example 15
Source File: PackageManagerServiceUtils.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private static File getSettingsProblemFile() {
    File dataDir = Environment.getDataDirectory();
    File systemDir = new File(dataDir, "system");
    File fname = new File(systemDir, "uiderrors.txt");
    return fname;
}
 
Example 16
Source File: AbstractStatsBase.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
protected AtomicFile getFile() {
    File dataDir = Environment.getDataDirectory();
    File systemDir = new File(dataDir, "system");
    File fname = new File(systemDir, mFileName);
    return new AtomicFile(fname);
}
 
Example 17
Source File: XSharedPreferences.java    From xposed-art with Apache License 2.0 4 votes vote down vote up
public XSharedPreferences(String packageName, String prefFileName) {
	mFile = new File(Environment.getDataDirectory(), "data/" + packageName + "/shared_prefs/" + prefFileName + ".xml");
	startLoadFromDisk();
}
 
Example 18
Source File: AppManagerEngine.java    From MobileGuard with MIT License 2 votes vote down vote up
/**
 * get the rom free space
 *
 * @return the byte of free space
 */
public static long getRomFreeSpace() {
    File directory = Environment.getDataDirectory();
    return directory.getFreeSpace();
}
 
Example 19
Source File: UserManagerService.java    From android_9.0.0_r45 with Apache License 2.0 2 votes vote down vote up
/**
 * 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());
}
 
Example 20
Source File: PathUtils.java    From DevUtils with Apache License 2.0 2 votes vote down vote up
/**
 * 获取 data 目录 - path /data
 * @return /system
 */
public File getDataDirectory() {
    return Environment.getDataDirectory();
}