下面列出了android.os.Environment#getDataDirectory ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
/**
* 开始导出数据 此操作比较耗时,建议在线程中进行
* @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;
}
@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;
}
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;
}
}
/** 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();
}
}
}
/**
* 获取手机内部总存储空间 单位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();
}
}
/**
* 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");
}
}
/**
* 获取手机内存存储可用空间
*
* @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();
}
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;
}
});
}
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);
}
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);
}
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);
}
/**
* 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);
}
}
public XSharedPreferences(String packageName, String prefFileName) {
mFile = new File(Environment.getDataDirectory(), "data/" + packageName + "/shared_prefs/" + prefFileName + ".xml");
startLoadFromDisk();
}
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;
}
public DeviceStateJB(Context context) {
this.context = context;
this.info = new DeviceInfo(context);
this.dataDirectory = Environment.getDataDirectory();
this.directoryStatus = new StatFs(dataDirectory.getPath());
}
/**
* 获取 data 目录 - path /data
* @return /system
*/
public File getDataDirectory() {
return Environment.getDataDirectory();
}
/**
* 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());
}
/**
* get the rom free space
*
* @return the byte of free space
*/
public static long getRomFreeSpace() {
File directory = Environment.getDataDirectory();
return directory.getFreeSpace();
}