Java Code Examples for android.os.Environment
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project agit, under directory /agit/src/main/java/com/madgag/agit/.
Source file: AgitModule.java

public ImageSession<String,Bitmap> get(){ Log.i("BRP","ImageSessionProvider INVOKED"); ImageProcessor<Bitmap> imageProcessor=new ScaledBitmapDrawableGenerator(34,resources); ImageResourceDownloader<String,Bitmap> downloader=new GravatarBitmapDownloader(); File file=new File(Environment.getExternalStorageDirectory(),"gravatars"); ImageResourceStore<String,Bitmap> imageResourceStore=new BitmapFileStore<String>(file); return new ImageSession<String,Bitmap>(imageProcessor,downloader,imageResourceStore,resources.getDrawable(R.drawable.loading_34_centred)); }
Example 2
From project AndroidCommon, under directory /src/com/asksven/android/common/utils/.
Source file: DataStorage.java

public static boolean isExternalStorageWritable(){ boolean mExternalStorageAvailable=false; boolean mExternalStorageWriteable=false; String state=Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { mExternalStorageAvailable=mExternalStorageWriteable=true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { mExternalStorageAvailable=true; mExternalStorageWriteable=false; } else { mExternalStorageAvailable=mExternalStorageWriteable=false; } return (mExternalStorageAvailable && mExternalStorageWriteable); }
Example 3
From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/helper/.
Source file: CSVHelper.java

public Uri prepareCSV(Session session) throws IOException { OutputStream outputStream=null; try { File storage=Environment.getExternalStorageDirectory(); File dir=new File(storage,"aircasting_sessions"); dir.mkdirs(); File file=new File(dir,fileName(session.getTitle())); outputStream=new FileOutputStream(file); Writer writer=new OutputStreamWriter(outputStream); CsvWriter csvWriter=new CsvWriter(writer,','); csvWriter.write("sensor:model"); csvWriter.write("sensor:package"); csvWriter.write("sensor:capability"); csvWriter.write("Date"); csvWriter.write("Time"); csvWriter.write("Timestamp"); csvWriter.write("geo:lat"); csvWriter.write("geo:long"); csvWriter.write("sensor:units"); csvWriter.write("Value"); csvWriter.endRecord(); write(session).toWriter(csvWriter); csvWriter.flush(); csvWriter.close(); Uri uri=Uri.fromFile(file); if (Constants.isDevMode()) { Log.i(Constants.TAG,"File path [" + uri + "]"); } return uri; } finally { closeQuietly(outputStream); } }
Example 4
From project Alerte-voirie-android, under directory /src/com/c4mprod/utils/.
Source file: ImageDownloader.java

/** * Download the specified image from the Internet and binds it to the provided ImageView. The binding is immediate if the image is found in the cache and will be done asynchronously otherwise. A null bitmap will be associated to the ImageView if an error occurs. * @param url * @param imageView * @param subfolder the subfolder in sdcard cache */ public void download(String url,ImageView imageView,String subfolder){ if (subfolder != null) { mSubfolder="/" + subfolder; } else { mSubfolder=""; } mfolder=Environment.getExternalStorageDirectory().getPath() + "/Android/data/" + imageView.getContext().getPackageName()+ "/files/images"+ mSubfolder; if (Environment.MEDIA_MOUNTED.equals(state)) { mExternalStorageAvailable=mExternalStorageWriteable=true; try { (new File(mfolder)).mkdirs(); (new File(mfolder + "/.nomedia")).createNewFile(); } catch ( IOException e) { e.printStackTrace(); } } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { mExternalStorageAvailable=true; mExternalStorageWriteable=false; } else { mExternalStorageAvailable=mExternalStorageWriteable=false; } resetPurgeTimer(); Bitmap bitmap=getBitmapFromCache(url); if (bitmap == null) { forceDownload(url,imageView); } else { cancelPotentialDownload(url,imageView); imageView.setImageBitmap(bitmap); imageView.setBackgroundDrawable(null); if (listener != null) { listener.onImageDownloaded(imageView,url,mfolder + "/" + URLEncoder.encode(url),imageView.getDrawable().getIntrinsicWidth(),imageView.getDrawable().getIntrinsicWidth()); } } }
Example 5
From project AmDroid, under directory /AmDroid/src/main/java/com/jaeckel/amenoid/util/.
Source file: HelloWorldMaker.java

public static void main(String[] args) throws Exception { DexMaker dexMaker=new DexMaker(); TypeId<?> helloWorld=TypeId.get("LHelloWorld;"); dexMaker.declare(helloWorld,"HelloWorld.generated",Modifier.PUBLIC,TypeId.OBJECT); generateHelloMethod(dexMaker,helloWorld); File outputDir=Environment.getExternalStorageDirectory(); ClassLoader loader=dexMaker.generateAndLoad(HelloWorldMaker.class.getClassLoader(),outputDir); Class<?> helloWorldClass=loader.loadClass("HelloWorld"); Log.d("helloWorldClass.getMethod(\"hello\").invoke(null);"); helloWorldClass.getMethod("hello").invoke(null); }
Example 6
From project and-bible, under directory /AndBible/src/net/bible/android/view/activity/.
Source file: StartupActivity.java

/** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.startup_view); TextView versionTextView=(TextView)findViewById(R.id.versionText); String versionMsg=BibleApplication.getApplication().getString(R.string.version_text,CommonUtils.getApplicationVersionName()); versionTextView.setText(versionMsg); int abortErrorMsgId=BibleApplication.getApplication().getErrorDuringStartup(); if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { abortErrorMsgId=R.string.no_sdcard_error; } if (abortErrorMsgId != 0) { Dialogs.getInstance().showErrorMsg(abortErrorMsgId,new Callback(){ @Override public void okay(){ finish(); } } ); return; } final Handler uiHandler=new Handler(); final Runnable uiThreadRunnable=new Runnable(){ @Override public void run(){ postBasicInitialisationControl(); } } ; new Thread(){ public void run(){ try { SwordDocumentFacade.getInstance().getBibles(); } finally { uiHandler.post(uiThreadRunnable); } } } .start(); }
Example 7
From project Android-automation, under directory /Tmts_Java/src/com/taobao/tmts/framework/.
Source file: TmtsLog.java

/** * Get the Sd Root path. * @return Sd Root path. */ private static File getSdRootPath(){ File sdDir=null; boolean sdCardExist=Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); if (sdCardExist) { sdDir=Environment.getExternalStorageDirectory(); return sdDir; } else { Log.i(LOG_TAG,"Sd Card not found"); } return null; }
Example 8
From project android-context, under directory /src/edu/fsu/cs/contextprovider/.
Source file: ContextExpandableListActivity.java

public void exportToFile() throws IOException { String path=Environment.getExternalStorageDirectory() + "/" + CSV_FILENAME; File file=new File(path); file.createNewFile(); if (!file.isFile()) { throw new IllegalArgumentException("Should not be a directory: " + file); } if (!file.canWrite()) { throw new IllegalArgumentException("File cannot be written: " + file); } Writer output=new BufferedWriter(new FileWriter(file)); HashMap<String,String> cntx=null; String line; cntx=ContextProvider.getAllUnordered(); for ( LinkedHashMap.Entry<String,String> entry : cntx.entrySet()) { ContextListItem item=new ContextListItem(); item.setName(entry.getKey()); item.setValue(entry.getValue()); line=item.toString(); output.write(line + "\n"); } output.close(); Toast.makeText(this,String.format("Saved",path),Toast.LENGTH_LONG).show(); Intent shareIntent=new Intent(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse("file://" + path)); shareIntent.setType("text/plain"); startActivity(Intent.createChooser(shareIntent,"Share Context Using...")); }
Example 9
From project android-cropimage, under directory /src/com/android/camera/.
Source file: ImageManager.java

/** * OSX requires plugged-in USB storage to have path /DCIM/NNNAAAAA to be imported. This is a temporary fix for bug#1655552. */ public static void ensureOSXCompatibleFolder(){ File nnnAAAAA=new File(Environment.getExternalStorageDirectory().toString() + "/DCIM/100ANDRO"); if ((!nnnAAAAA.exists()) && (!nnnAAAAA.mkdir())) { Log.e(TAG,"create NNNAAAAA file: " + nnnAAAAA.getPath() + " failed"); } }
Example 10
From project Android-FFXIEQ, under directory /ffxieq/src/com/github/kanata3249/ffxieq/android/db/.
Source file: FFXIDatabase.java

public FFXIDatabase(Context context,boolean useExternal,FFXIEQSettings settings){ super(context,DB_NAME,null,1); DB_PATH=Environment.getDataDirectory() + "/data/" + context.getPackageName()+ "/databases/"; SD_PATH=Environment.getExternalStorageDirectory() + "/" + context.getPackageName()+ "/"; EXTERNAL_SD_PATH=Environment.getExternalStorageDirectory() + "/external_sd/" + context.getPackageName()+ "/"; mContext=context; mHpTable=new HPTable(); mMpTable=new MPTable(); mJobRankTable=new JobRankTable(); mSkillCapTable=new SkillCapTable(); mStatusTable=new StatusTable(); mEquipmentTable=new EquipmentTable(); mAtmaTable=new AtmaTable(); mJobTraitTable=new JobTraitTable(); mMeritPointTable=new MeritPointTable(); mFoodTable=new FoodTable(); mMagicTable=new MagicTable(); mVWAtmaTable=new VWAtmaTable(); mBlueMagicTable=new BlueMagicTable(); mStringTable=new StringTable(); if (useExternal) mDBPath=SD_PATH; else mDBPath=DB_PATH; mUseExternalDB=useExternal; mSettings=settings; try { if (checkDatabase(mDBPath)) { copyDatabaseFromAssets(mDBPath); } } catch ( IOException e) { } }
Example 11
From project Android-File-Manager, under directory /src/com/nexes/manager/.
Source file: DirectoryInfo.java

protected Long doInBackground(String... vals){ FileManager flmg=new FileManager(); 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; }
Example 12
From project Android-File-Manager-Tablet, under directory /src/com/nexes/manager/tablet/.
Source file: DirListActivity.java

@Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); String storage="/" + Environment.getExternalStorageDirectory().getName(); mContext=getActivity(); mDirList=new ArrayList<String>(); mBookmarkNames=new ArrayList<String>(); mDirListString=(PreferenceManager.getDefaultSharedPreferences(mContext)).getString(SettingsActivity.PREF_LIST_KEY,""); mBookmarkString=(PreferenceManager.getDefaultSharedPreferences(mContext)).getString(SettingsActivity.PREF_BOOKNAME_KEY,""); if (mDirListString.length() > 0) { String[] l=mDirListString.split(":"); for ( String string : l) mDirList.add(string); } else { mDirList.add("/"); mDirList.add(storage); mDirList.add(storage + "/" + "Download"); mDirList.add(storage + "/" + "Music"); mDirList.add(storage + "/" + "Movies"); mDirList.add(storage + "/" + "Pictures"); mDirList.add("Bookmarks"); } if (mBookmarkString.length() > 0) { String[] l=mBookmarkString.split(":"); for ( String string : l) mBookmarkNames.add(string); } }
Example 13
From project android-ocr, under directory /android/src/edu/sfsu/cs/orange/ocr/.
Source file: CaptureActivity.java

/** * Finds the proper location on the SD card where we can save files. */ private File getStorageDirectory(){ String state=null; try { state=Environment.getExternalStorageState(); } catch ( RuntimeException e) { Log.e(TAG,"Is the SD card visible?",e); showErrorMessage("Error","Required external storage (such as an SD card) is unavailable."); } if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { try { return getExternalFilesDir(Environment.MEDIA_MOUNTED); } catch ( NullPointerException e) { Log.e(TAG,"External storage is unavailable"); showErrorMessage("Error","Required external storage (such as an SD card) is full or unavailable."); } } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { Log.e(TAG,"External storage is read-only"); showErrorMessage("Error","Required external storage (such as an SD card) is unavailable for data storage."); } else { Log.e(TAG,"External storage is unavailable"); showErrorMessage("Error","Required external storage (such as an SD card) is unavailable or corrupted."); } return null; }
Example 14
From project android-rackspacecloud, under directory /src/com/rackspacecloud/android/.
Source file: ContainerObjectDetails.java

private boolean storageIsReady(){ boolean mExternalStorageAvailable=false; boolean mExternalStorageWriteable=false; String state=Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { mExternalStorageAvailable=mExternalStorageWriteable=true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { mExternalStorageAvailable=true; mExternalStorageWriteable=false; } else { mExternalStorageAvailable=mExternalStorageWriteable=false; } return mExternalStorageAvailable && mExternalStorageWriteable; }
Example 15
From project android-sdk, under directory /src/test/java/com/mobeelizer/mobile/android/.
Source file: MobeelizerFileServiceTest.java

@Before public void init() throws Exception { PowerMockito.mockStatic(Log.class); PowerMockito.when(Log.i(anyString(),anyString())).thenReturn(1); PowerMockito.mockStatic(Environment.class); File externalStorageDirectory=mock(File.class); when(externalStorageDirectory.getAbsolutePath()).thenReturn("externalPath"); PowerMockito.when(Environment.getExternalStorageDirectory()).thenReturn(externalStorageDirectory); directory=mock(File.class); PowerMockito.whenNew(File.class).withArguments("externalPath" + File.separator + "mobeelizer"+ File.separator+ "application"+ File.separator+ "instance"+ File.separator+ "user"+ File.separator).thenReturn(directory); uuid=UUID.randomUUID(); PowerMockito.mockStatic(UUID.class); PowerMockito.when(UUID.randomUUID()).thenReturn(uuid); MobeelizerApplication application=mock(MobeelizerApplication.class); when(application.getInstance()).thenReturn("instance"); when(application.getUser()).thenReturn("user"); when(application.getApplication()).thenReturn("application"); database=mock(MobeelizerDatabaseImpl.class); when(application.getDatabase()).thenReturn(database); fileService=new MobeelizerFileService(application); }
Example 16
From project android-shuffle, under directory /client/src/org/dodgybits/shuffle/android/preference/activity/.
Source file: PreferencesCreateBackupActivity.java

public Void doInBackground(String... filename){ try { String message=getString(R.string.status_checking_media); Log.d(cTag,message); publishProgress(Progress.createProgress(0,message)); String storage_state=Environment.getExternalStorageState(); if (!Environment.MEDIA_MOUNTED.equals(storage_state)) { message=getString(R.string.warning_media_not_mounted,storage_state); reportError(message); } else { File dir=Environment.getExternalStorageDirectory(); final File backupFile=new File(dir,filename[0]); message=getString(R.string.status_creating_backup); Log.d(cTag,message); publishProgress(Progress.createProgress(5,message)); if (backupFile.exists()) { publishProgress(Progress.createErrorProgress("",new Runnable(){ @Override public void run(){ showFileExistsWarning(backupFile); } } )); } else { backupFile.createNewFile(); FileOutputStream out=new FileOutputStream(backupFile); writeBackup(out); } } } catch ( Exception e) { String message=getString(R.string.warning_backup_failed,e.getMessage()); reportError(message); } return null; }
Example 17
From project android-xbmcremote, under directory /src/org/xbmc/android/util/.
Source file: ImportUtilities.java

/** * Returns number of free bytes on the SD card. * @return Number of free bytes on the SD card. */ public static long freeSpace(){ StatFs stat=new StatFs(Environment.getExternalStorageDirectory().getPath()); long blockSize=stat.getBlockSize(); long availableBlocks=stat.getAvailableBlocks(); return availableBlocks * blockSize; }
Example 18
From project androidquery, under directory /demo/src/com/androidquery/test/async/.
Source file: AjaxLoadingActivity.java

public void async_file_custom(){ String url="https://picasaweb.google.com/data/feed/base/featured?max-results=16"; File ext=Environment.getExternalStorageDirectory(); File target=new File(ext,"aquery/myfolder2/photos1.xml"); aq.progress(R.id.progress).download(url,target,new AjaxCallback<File>(){ public void callback( String url, File file, AjaxStatus status){ if (file != null) { showResult("File:" + file.length() + ":"+ file,status); } else { showResult("Failed",status); } } } ); }
Example 19
From project AndroidSensorLogger, under directory /src/com/sstp/androidsensorlogger/.
Source file: AndroidSensorLoggerActivity.java

public void SaveData(String lat,String lon,String alt,String time,String fileLocation) throws Exception { try { File root=Environment.getExternalStorageDirectory(); if (root.canWrite()) { File gpxfile=new File(root,fileLocation); FileWriter gpxwriter=new FileWriter(gpxfile,true); CSVWriter out=new CSVWriter(gpxwriter); String[] log=new String[]{lat,lon,alt,time}; out.writeNext(log); out.flush(); } } catch ( IOException e) { e.printStackTrace(); } }
Example 20
From project androidTileMapEditor_1, under directory /src/it/sineo/android/tileMapEditor/.
Source file: TiledMapActivity.java

public boolean onCreateOptionsMenu(Menu menu){ com.actionbarsherlock.view.MenuInflater inflater=getSupportMenuInflater(); inflater.inflate(R.menu.tiledmap,menu); menu.findItem(R.id.tiledMap_menu_save).setEnabled(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)); return true; }
Example 21
From project android_aosp_packages_apps_Settings, under directory /src/com/android/settings/deviceinfo/.
Source file: Memory.java

@Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,Preference preference){ String clickedItem=preference.getKey(); if (mountToggles.containsKey(clickedItem)) { String path=mountToggles.get(clickedItem); String status=new String(); try { status=getMountService().getVolumeState(path); } catch ( RemoteException ex) { status=Environment.MEDIA_UNMOUNTED; } if (status.equals(Environment.MEDIA_MOUNTED)) { unmount(path); } else { mount(path); } return true; } else if (formatToggles.containsKey(clickedItem)) { String path=formatToggles.get(clickedItem); Intent intent=new Intent(Intent.ACTION_VIEW); intent.putExtra("path",path); intent.setClass(this,com.android.settings.MediaFormat.class); startActivity(intent); return true; } return false; }
Example 22
From project android_packages_apps_cmparts, under directory /src/com/cyanogenmod/cmparts/activities/.
Source file: LockscreenUnlockActivity.java

private boolean doesUnlockAbilityExist(){ final File mStoreFile=new File(Environment.getDataDirectory(),"/misc/lockscreen_gestures"); boolean GestureCanUnlock=false; boolean GestureEnabled=Settings.System.getInt(getContentResolver(),Settings.System.LOCKSCREEN_GESTURES_ENABLED,0) == 1; boolean trackCanUnlock=Settings.System.getInt(getContentResolver(),Settings.System.TRACKBALL_UNLOCK_SCREEN,0) == 1; boolean menuCanUnlock=Settings.System.getInt(getContentResolver(),Settings.System.MENU_UNLOCK_SCREEN,0) == 1; if (GestureEnabled) { GestureLibrary gl=GestureLibraries.fromFile(mStoreFile); if (gl.load()) { for ( String name : gl.getGestureEntries()) { String[] payload=name.split("___",2); if ("UNLOCK".equals(payload[1])) { GestureCanUnlock=true; break; } } } } if (GestureCanUnlock || trackCanUnlock || menuCanUnlock) { return true; } else { return false; } }
Example 23
From project android_packages_apps_FileManager, under directory /src/org/openintents/filemanager/.
Source file: SaveAsActivity.java

private String getPath(Uri uri){ Uri sd=Uri.fromFile(Environment.getExternalStorageDirectory()); if (uri.getHost().equals("gmail-ls")) { Cursor cur=managedQuery(uri,new String[]{"_display_name"},null,null,null); int nameColumn=cur.getColumnIndex("_display_name"); if (cur.moveToFirst()) { return sd.buildUpon().appendPath(cur.getString(nameColumn)).toString(); } } return sd.getPath(); }
Example 24
From project android_packages_apps_Gallery, under directory /src/com/android/camera/.
Source file: Camera.java

private void updateStorageHint(int remaining){ String noStorageText=null; if (remaining == MenuHelper.NO_STORAGE_ERROR) { String state=Environment.getExternalStorageState(); if (state == Environment.MEDIA_CHECKING || ImageManager.isMediaScannerScanning(getContentResolver())) { noStorageText=getString(R.string.preparing_sd); } else { noStorageText=getString(R.string.no_storage); } } else if (remaining < 1) { noStorageText=getString(R.string.not_enough_space); } if (noStorageText != null) { if (mStorageHint == null) { mStorageHint=OnScreenHint.makeText(this,noStorageText); } else { mStorageHint.setText(noStorageText); } mStorageHint.show(); } else if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint=null; } }
Example 25
From project android_packages_apps_Gallery2, under directory /src/com/android/gallery3d/data/.
Source file: MtpContext.java

public boolean copyFile(String deviceName,MtpObjectInfo objInfo){ if (GalleryUtils.hasSpaceForSize(objInfo.getCompressedSize())) { File dest=Environment.getExternalStorageDirectory(); dest=new File(dest,BucketNames.IMPORTED); dest.mkdirs(); String destPath=new File(dest,objInfo.getName()).getAbsolutePath(); int objectId=objInfo.getObjectHandle(); if (mClient.importFile(deviceName,objectId,destPath)) { mScannerClient.scanPath(destPath); return true; } } else { Log.w(TAG,"No space to import " + objInfo.getName() + " whose size = "+ objInfo.getCompressedSize()); } return false; }
Example 26
From project android_packages_apps_Gallery3D, under directory /src/com/cooliris/cache/.
Source file: BootReceiver.java

@Override public void onReceive(final Context context,Intent intent){ final String action=intent.getAction(); final Uri fileUri=intent.getData(); Log.i(TAG,"Got intent with action " + action); if (Intent.ACTION_MEDIA_SCANNER_FINISHED.equals(action)) { if (Environment.getExternalStorageDirectory().getPath().equals(fileUri.getPath())) { CacheService.markDirty(); CacheService.startCache(context,true); } } else if (Intent.ACTION_MEDIA_MOUNTED.equals(action)) { ; } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)) { final long bucketId=Utils.getBucketIdFromUri(context.getContentResolver(),fileUri); if (!CacheService.isPresentInCache(bucketId)) { CacheService.markDirty(); } } else if (action.equals(Intent.ACTION_MEDIA_EJECT)) { LocalDataSource.sThumbnailCache.close(); LocalDataSource.sThumbnailCacheVideo.close(); PicasaDataSource.sThumbnailCache.close(); CacheService.sAlbumCache.close(); CacheService.sMetaAlbumCache.close(); CacheService.sSkipThumbnailIds.flush(); } }
Example 27
From project android_packages_apps_Nfc, under directory /src/com/android/nfc/handover/.
Source file: HandoverManager.java

boolean checkMediaStorage(File path){ if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { if (!path.isDirectory() && !path.mkdir()) { Log.e(TAG,"Not dir or not mkdir " + path.getAbsolutePath()); return false; } return true; } else { Log.e(TAG,"External storage not mounted, can't store file."); return false; } }
Example 28
From project android_packages_apps_Superuser, under directory /src/com/noshufou/android/su/util/.
Source file: BackupUtil.java

public static boolean makeBackup(Context context){ boolean status=false; FileOutputStream file=null; XmlSerializer serializer=Xml.newSerializer(); try { file=new FileOutputStream(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/subackup.xml")); serializer.setOutput(file,"UTF-8"); serializer.startDocument(null,true); serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output",true); serializer.startTag("","backup"); status=backupApps(context,serializer); status=backupPrefs(context,serializer); serializer.endTag("","backup"); serializer.endDocument(); serializer.flush(); file.close(); } catch ( IllegalArgumentException e) { Log.e(TAG,"IllegalArgumentException",e); return false; } catch ( IllegalStateException e) { Log.e(TAG,"IllegalStateException",e); return false; } catch ( IOException e) { Log.e(TAG,"IOException",e); return false; } return status; }
Example 29
From project androlog, under directory /androlog/src/main/java/de/akquinet/android/androlog/.
Source file: LogHelper.java

/** * Gets an input on a configuration file placed on the the SDCard. * @param fileName the file name * @return the input stream to read the file or <code>null</code> if thefile does not exist. */ protected static InputStream getConfigurationFileFromSDCard(String fileName){ File sdcard=Environment.getExternalStorageDirectory(); if (sdcard == null || !sdcard.exists() || !sdcard.canRead()) { return null; } String sdCardPath=sdcard.getAbsolutePath(); File propFile=new File(sdCardPath + "/" + fileName); if (!propFile.exists()) { return null; } FileInputStream fileIs=null; try { fileIs=new FileInputStream(propFile); } catch ( FileNotFoundException e) { return null; } return fileIs; }
Example 30
From project andstatus, under directory /src/org/andstatus/app/.
Source file: PreferencesActivity.java

protected void showUseExternalStorage(){ boolean use=MyPreferences.getDefaultSharedPreferences().getBoolean(MyPreferences.KEY_USE_EXTERNAL_STORAGE,false); if (use != mUseExternalStorage.isChecked()) { MyPreferences.getDefaultSharedPreferences().edit().putBoolean(MyPreferences.KEY_USE_EXTERNAL_STORAGE_NEW,use).commit(); mUseExternalStorage.setChecked(use); } if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && !mUseExternalStorage.isChecked()) { mUseExternalStorage.setEnabled(false); } }
Example 31
From project Anki-Android, under directory /src/com/ichi2/anki/.
Source file: CustomExceptionHandler.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; }
Example 32
From project AnySoftKeyboard, under directory /src/com/anysoftkeyboard/ui/settings/.
Source file: UserDictionaryEditorActivity.java

@Override protected Void doInBackground(Void... params){ try { final File externalFolder=Environment.getExternalStorageDirectory(); final File targetFolder=new File(externalFolder,"/Android/data/" + getPackageName() + "/files/"); targetFolder.mkdirs(); XmlWriter output=new XmlWriter(new File(targetFolder,ASK_USER_WORDS_SDCARD_FILENAME)); output.writeEntity("userwordlist"); for ( String locale : mLocalesToSave) { EditableDictionary dictionary=DictionaryFactory.getInstance().createUserDictionary(getApplicationContext(),locale); Log.d(TAG,"Reading words from user dictionary locale " + locale); if (dictionary != mCurrentDictionary && mCurrentDictionary != null) mCurrentDictionary.close(); mCurrentDictionary=dictionary; mCursor=mCurrentDictionary.getWordsCursor(); output.writeEntity("wordlist").writeAttribute("locale",locale); mCursor.moveToFirst(); final int wordIndex=mCursor.getColumnIndex(Words.WORD); final int freqIndex=mCursor.getColumnIndex(Words.FREQUENCY); while (!mCursor.isAfterLast()) { String word=mCursor.getString(wordIndex).trim(); int freq=mCursor.getInt(freqIndex); output.writeEntity("w").writeAttribute("f",Integer.toString(freq)).writeText(word).endEntity(); if (AnyApplication.DEBUG) Log.d(TAG,"Storing word '" + word + "' with freq "+ freq); mCursor.moveToNext(); } output.endEntity(); } output.endEntity(); output.close(); } catch ( Exception e) { mException=e; e.printStackTrace(); } return null; }
Example 33
public static Bundle exportKeyRings(Activity context,Vector<Integer> keyRingIds,OutputStream outStream,ProgressDialogUpdater progress) throws GeneralException, FileNotFoundException, PGPException, IOException { Bundle returnData=new Bundle(); if (keyRingIds.size() == 1) { progress.setProgress(R.string.progress_exportingKey,0,100); } else { progress.setProgress(R.string.progress_exportingKeys,0,100); } if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { throw new GeneralException(context.getString(R.string.error_externalStorageNotReady)); } ArmoredOutputStream out=new ArmoredOutputStream(outStream); int numKeys=0; for (int i=0; i < keyRingIds.size(); ++i) { progress.setProgress(i * 100 / keyRingIds.size(),100); Object obj=mDatabase.getKeyRing(keyRingIds.get(i)); PGPPublicKeyRing publicKeyRing; PGPSecretKeyRing secretKeyRing; if (obj instanceof PGPSecretKeyRing) { secretKeyRing=(PGPSecretKeyRing)obj; secretKeyRing.encode(out); } else if (obj instanceof PGPPublicKeyRing) { publicKeyRing=(PGPPublicKeyRing)obj; publicKeyRing.encode(out); } else { continue; } ++numKeys; } out.close(); returnData.putInt("exported",numKeys); progress.setProgress(R.string.progress_done,100,100); return returnData; }
Example 34
From project apps-for-android, under directory /LolcatBuilder/src/com/android/lolcat/.
Source file: LolcatActivity.java

/** * Saves the LolcatView's working Bitmap to the SD card, in preparation for viewing it later and/or sharing it. The bitmap will be saved as a new file in the directory LOLCAT_SAVE_DIRECTORY, with an automatically-generated filename based on the current time. It also connects to the MediaScanner service, since we'll need to scan that new file (in order to get a Uri we can then VIEW or share.) This method is run in a worker thread; @see saveImage(). */ private void saveImageInternal(){ Log.i(TAG,"saveImageInternal()..."); String filename=Environment.getExternalStorageDirectory() + "/" + LOLCAT_SAVE_DIRECTORY+ String.valueOf(System.currentTimeMillis() + SAVED_IMAGE_EXTENSION); Log.i(TAG,"- filename: '" + filename + "'"); if (ensureFileExists(filename)) { try { OutputStream outstream=new FileOutputStream(filename); Bitmap bitmap=mLolcatView.getWorkingBitmap(); boolean success=bitmap.compress(SAVED_IMAGE_COMPRESS_FORMAT,100,outstream); Log.i(TAG,"- success code from Bitmap.compress: " + success); outstream.close(); if (success) { Log.i(TAG,"- Saved! filename = " + filename); mSavedImageFilename=filename; mMediaScannerConnection.connect(); } else { Log.w(TAG,"Bitmap.compress failed: bitmap " + bitmap + ", filename '"+ filename+ "'"); onSaveFailed(R.string.lolcat_save_failed); } } catch ( FileNotFoundException e) { Log.w(TAG,"error creating file",e); onSaveFailed(R.string.lolcat_save_failed); } catch ( IOException e) { Log.w(TAG,"error creating file",e); onSaveFailed(R.string.lolcat_save_failed); } } else { Log.w(TAG,"ensureFileExists failed for filename '" + filename + "'"); onSaveFailed(R.string.lolcat_save_failed); } }
Example 35
From project Backyard-Brains-Android-App, under directory /src/com/backyardbrains/.
Source file: FileListActivity.java

@Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.file_list); bybDirectory=new File(Environment.getExternalStorageDirectory() + "/BackyardBrains/"); rescanFiles(); }
Example 36
From project beintoo-android-sdk, under directory /BeintooSDK/src/com/beintoo/beintoosdkutility/.
Source file: SDFileManager.java

public boolean isAvailable(){ boolean mExternalStorageWriteable=false; String state=Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { mExternalStorageWriteable=true; } else { mExternalStorageWriteable=false; } return mExternalStorageWriteable; }
Example 37
From project BF3-Battlelog, under directory /src/com/coveragemapper/android/Map/.
Source file: ExternalCacheDirectory.java

@Override public File getExternalCacheDirectory(){ final String cachePath=Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + mContext.getPackageName()+ "/cache/"; final File file=new File(cachePath); file.mkdirs(); return file; }
Example 38
From project BibleQuote-for-Android, under directory /src/com/BibleQuote/controllers/.
Source file: LibraryController.java

public static LibraryController create(LibrarySource librarySource,EventManager eventManager,Context context){ String libraryPath; File libraryDir; switch (librarySource) { case FileSystem: libraryPath=Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ? DataConstants.FS_EXTERNAL_DATA_PATH : DataConstants.FS_DATA_PATH; libraryDir=new File(libraryPath); CacheContext cacheContext=new CacheContext(context.getCacheDir(),DataConstants.LIBRARY_CACHE); CacheModuleController<FsModule> cache=new CacheModuleController<FsModule>(cacheContext); FsLibraryContext fsLibraryContext=new FsLibraryContext(libraryDir,context,cache); return new LibraryController(new FsLibraryUnitOfWork(fsLibraryContext,cacheContext)); case LocalDb: libraryPath=Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ? DataConstants.DB_EXTERNAL_DATA_PATH : DataConstants.DB_DATA_PATH; libraryDir=new File(libraryPath); DbLibraryContext dbLibraryContext=new DbLibraryContext(libraryDir,context); return new LibraryController(new DbLibraryUnitOfWork(dbLibraryContext),eventManager); default : break; } return null; }
Example 39
From project Bitcoin-Wallet-for-Android, under directory /wallet/src/de/schildbach/wallet/ui/.
Source file: WalletActivity.java

@Override public boolean onPrepareOptionsMenu(final Menu menu){ super.onPrepareOptionsMenu(menu); final String externalStorageState=Environment.getExternalStorageState(); menu.findItem(R.id.wallet_options_import_keys).setEnabled(Environment.MEDIA_MOUNTED.equals(externalStorageState) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(externalStorageState)); menu.findItem(R.id.wallet_options_export_keys).setEnabled(Environment.MEDIA_MOUNTED.equals(externalStorageState)); return true; }
Example 40
From project BombusLime, under directory /src/org/bombusim/lime/activity/.
Source file: LoggerActivity.java

private void saveLog(){ String state=Environment.getExternalStorageState(); if (!Environment.MEDIA_MOUNTED.equals(state)) { Toast.makeText(this,R.string.cantWriteStorage,Toast.LENGTH_LONG).show(); return; } File externalRoot=Environment.getExternalStorageDirectory(); Time tf=new Time(Time.getCurrentTimezone()); tf.set(System.currentTimeMillis()); String fn="BombusLime_" + tf.format2445() + ".txt"; File log=new File(externalRoot,fn); ArrayList<LoggerEvent> events=Lime.getInstance().getLog().getLogRecords(); try { PrintStream ps=new PrintStream(log); for ( LoggerEvent event : events) { ps.print(event.eventTypeName()); ps.print(' '); tf.set(event.timestamp); ps.print(tf.format3339(false)); ps.print(' '); ps.println(event.title); if (event.message != null) { ps.println(event.message); ps.println(); } } ps.close(); } catch ( FileNotFoundException e) { Toast.makeText(this,R.string.cantWriteStorage,Toast.LENGTH_LONG).show(); e.printStackTrace(); return; } Toast.makeText(this,"Log saved to " + externalRoot.getAbsolutePath() + '/'+ fn,Toast.LENGTH_LONG).show(); }
Example 41
From project Book-Catalogue, under directory /src/com/eleybourn/bookcatalogue/.
Source file: CropCropImage.java

public static void showStorageToast(Activity activity,int remaining){ String noStorageText=null; if (remaining == NO_STORAGE_ERROR) { String state=Environment.getExternalStorageState(); if (state == Environment.MEDIA_CHECKING) { noStorageText="Preparing card"; } else { noStorageText="No storage card"; } } else if (remaining < 1) { noStorageText="Not enough space"; } if (noStorageText != null) { Toast.makeText(activity,noStorageText,5000).show(); } }
Example 42
From project BSPAN---Bluetooth-Sensor-Processing-for-Android, under directory /AndroidSpineExample/src/com/t2/androidspineexample/.
Source file: LogWriter.java

public void open(String fileName){ mFileName=fileName; try { File root=Environment.getExternalStorageDirectory(); if (root.canWrite()) { mLogFile=new File(root,fileName); mFileName=mLogFile.getAbsolutePath(); FileWriter gpxwriter=new FileWriter(mLogFile,true); mLogWriter=new BufferedWriter(gpxwriter); } else { Log.e(TAG,"Cannot write to log file"); AlertDialog.Builder alert=new AlertDialog.Builder(mContext); alert.setTitle("ERROR"); alert.setMessage("Cannot write to log file"); alert.setPositiveButton("Ok",new DialogInterface.OnClickListener(){ public void onClick( DialogInterface dialog, int whichButton){ } } ); alert.show(); } } catch ( IOException e) { Log.e(TAG,"Cannot write to log file" + e.getMessage()); AlertDialog.Builder alert=new AlertDialog.Builder(mContext); alert.setTitle("ERROR"); alert.setMessage("Cannot write to file"); alert.setPositiveButton("Ok",new DialogInterface.OnClickListener(){ public void onClick( DialogInterface dialog, int whichButton){ } } ); alert.show(); } }
Example 43
From project Cafe, under directory /testservice/src/com/baidu/cafe/remote/.
Source file: SystemLib.java

/** * get available internal memory * @return byte value, can be formated to string by formatSize(long size)function<br/> e.g. 135553024 */ public long getMemoryInternalAvail(){ StatFs stat=new StatFs(Environment.getDataDirectory().getPath()); long blockSize=stat.getBlockSize(); long availableBlocks=stat.getAvailableBlocks(); return availableBlocks * blockSize; }
Example 44
From project callmeter, under directory /src/de/ub0r/android/callmeter/data/.
Source file: DataProvider.java

@Override public ParcelFileDescriptor openFile(final Uri uri,final String mode) throws FileNotFoundException { Log.d(TAG,"openFile(" + uri.toString() + ")"); final File d=Environment.getExternalStorageDirectory(); String fn=null; if (uri.equals(EXPORT_RULESET_URI)) { fn=DataProvider.EXPORT_RULESET_FILE; } else if (uri.equals(EXPORT_LOGS_URI)) { fn=DataProvider.EXPORT_LOGS_FILE; } else if (uri.equals(EXPORT_NUMGROUPS_URI)) { fn=DataProvider.EXPORT_NUMGROUPS_FILE; } else if (uri.equals(EXPORT_HOURGROUPS_URI)) { fn=DataProvider.EXPORT_HOURGROUPS_FILE; } if (fn == null) { return null; } final File f=new File(d,PACKAGE + File.separator + fn); return ParcelFileDescriptor.open(f,ParcelFileDescriptor.MODE_READ_ONLY); }
Example 45
private boolean SDCardAvailable(){ File storageRoot=Environment.getExternalStorageDirectory(); File appStorageRoot=new File(storageRoot,"chmi"); if (appStorageRoot.exists()) { File testFile=new File(appStorageRoot,"test_file"); if (testFile.exists()) { return testFile.delete(); } else { try { testFile.createNewFile(); testFile.delete(); return true; } catch ( IOException e) { return false; } } } else { return appStorageRoot.mkdirs(); } }
Example 46
From project CineShowTime-Android, under directory /Libraries/CineShowTime/src/com/binomed/showtime/android/util/.
Source file: CineShowTimeLayoutUtils.java

public static InputStream existFile(String urlImg,String fileName){ InputStream stream=null; try { File root=Environment.getExternalStorageDirectory(); if (fileName == null) { fileName=urlImg.substring(urlImg.lastIndexOf("/"),urlImg.length()); } File posterFile=new File(root,new StringBuilder(CineShowtimeCst.FOLDER_POSTER).append(fileName).toString()); posterFile.getParentFile().mkdirs(); if (posterFile.exists()) { Log.i(TAG,"img existe"); stream=new FileInputStream(posterFile); } } catch ( IOException e) { Log.e(TAG,"Could not write file " + e.getMessage()); } return stream; }
Example 47
From project cmsandroid, under directory /src/com/zia/freshdocs/app/.
Source file: CMISApplication.java

/** * Determines the application storage path. For now /sdcard/com.zia.freshdocs. * @return */ protected StringBuilder getAppStoragePath(){ StringBuilder targetPath=new StringBuilder(); File sdCard=Environment.getExternalStorageDirectory(); if (sdCard != null) { targetPath.append(sdCard.getAbsolutePath()).append(File.separator); String packageName=Constants.class.getPackage().getName(); targetPath.append(packageName); } return targetPath; }
Example 48
From project Common-Sense-Net-2, under directory /RealFarm/src/com/commonsensenet/realfarm/ownCamera/.
Source file: OwnCameraActivity.java

/** * Create a File for saving the image */ private static File getOutputMediaFile(int type){ File mediaStorageDir=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"OwnCamera"); if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d("OwnCamera","failed to create directory"); return null; } } String timeStamp=new SimpleDateFormat(DATE_FORMAT).format(new Date()); File mediaFile; if (type == MEDIA_TYPE_IMAGE) { mediaFile=new File(String.format(FILENAME_FORMAT,mediaStorageDir.getPath(),File.separator,timeStamp)); } else { return null; } return mediaFile; }
Example 49
From project connectbot, under directory /src/sk/vx/connectbot/service/.
Source file: TerminalBridge.java

/** * Create a screenshot of the current view */ public void captureScreen(){ String msg; File dir, path; boolean success=true; Bitmap screenshot=this.bitmap; if (manager == null || parent == null || screenshot == null) return; SimpleDateFormat s=new SimpleDateFormat("yyyyMMdd_HHmmss"); String date=s.format(new Date()); String pref_path=manager.prefs.getString(PreferenceConstants.SCREEN_CAPTURE_FOLDER,""); File default_path=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); if (pref_path.equals("")) dir=default_path; else dir=new File(pref_path); path=new File(dir,"vx-" + date + ".png"); try { dir.mkdirs(); FileOutputStream out=new FileOutputStream(path); screenshot.compress(Bitmap.CompressFormat.PNG,90,out); out.close(); } catch ( Exception e) { e.printStackTrace(); success=false; } if (success) { msg=manager.getResources().getString(R.string.screenshot_saved_as) + " " + path; if (manager.prefs.getBoolean(PreferenceConstants.SCREEN_CAPTURE_POPUP,true)) { new AlertDialog.Builder(parent.getContext()).setTitle(R.string.screenshot_success_title).setMessage(msg).setPositiveButton(R.string.button_close,null).show(); } } else { msg=manager.getResources().getString(R.string.screenshot_not_saved_as) + " " + path; new AlertDialog.Builder(parent.getContext()).setTitle(R.string.screenshot_error_title).setMessage(msg).setNegativeButton(R.string.button_close,null).show(); } return; }
Example 50
From project cornerstone, under directory /frameworks/base/services/java/com/android/server/am/.
Source file: ActivityManagerService.java

private static File getCalledPreBootReceiversFile(){ File dataDir=Environment.getDataDirectory(); File systemDir=new File(dataDir,"system"); File fname=new File(systemDir,"called_pre_boots.dat"); return fname; }
Example 51
From project COSsettings, under directory /src/com/cyanogenmod/cmparts/activities/.
Source file: LockscreenUnlockActivity.java

private boolean doesUnlockAbilityExist(){ final File mStoreFile=new File(Environment.getDataDirectory(),"/misc/lockscreen_gestures"); boolean GestureCanUnlock=false; boolean GestureEnabled=Settings.System.getInt(getContentResolver(),Settings.System.LOCKSCREEN_GESTURES_ENABLED,0) == 1; boolean trackCanUnlock=Settings.System.getInt(getContentResolver(),Settings.System.TRACKBALL_UNLOCK_SCREEN,0) == 1; boolean menuCanUnlock=Settings.System.getInt(getContentResolver(),Settings.System.MENU_UNLOCK_SCREEN,0) == 1; if (GestureEnabled) { GestureLibrary gl=GestureLibraries.fromFile(mStoreFile); if (gl.load()) { for ( String name : gl.getGestureEntries()) { String[] payload=name.split("___",2); if ("UNLOCK".equals(payload[1])) { GestureCanUnlock=true; break; } } } } if (GestureCanUnlock || trackCanUnlock || menuCanUnlock) { return true; } else { return false; } }
Example 52
From project creamed_glacier_app_settings, under directory /src/com/android/settings/applications/.
Source file: InstalledAppDetails.java

private void initMoveButton(){ if (Environment.isExternalStorageEmulated()) { mMoveAppButton.setVisibility(View.INVISIBLE); return; } boolean dataOnly=false; dataOnly=(mPackageInfo == null) && (mAppEntry != null); boolean moveDisable=true; if (dataOnly) { mMoveAppButton.setText(R.string.move_app); } else if ((mAppEntry.info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) { mMoveAppButton.setText(R.string.move_app_to_internal); moveDisable=false; } else { mMoveAppButton.setText(R.string.move_app_to_sdcard); mCanBeOnSdCardChecker.init(); moveDisable=!mCanBeOnSdCardChecker.check(mAppEntry.info); } if (moveDisable) { mMoveAppButton.setEnabled(false); } else { mMoveAppButton.setOnClickListener(this); mMoveAppButton.setEnabled(true); } }
Example 53
From project cropimage, under directory /src/com/droid4you/util/cropimage/.
Source file: CropImage.java

public static void showStorageToast(Activity activity,int remaining){ String noStorageText=null; if (remaining == NO_STORAGE_ERROR) { String state=Environment.getExternalStorageState(); if (state == Environment.MEDIA_CHECKING) { noStorageText="Preparing card"; } else { noStorageText="No storage card"; } } else if (remaining < 1) { noStorageText="Not enough space"; } if (noStorageText != null) { Toast.makeText(activity,noStorageText,5000).show(); } }
Example 54
From project cw-advandroid, under directory /Camera/Picture/src/com/commonsware/android/picture/.
Source file: PictureDemo.java

@Override protected String doInBackground(byte[]... jpeg){ File photo=new File(Environment.getExternalStorageDirectory(),"photo.jpg"); if (photo.exists()) { photo.delete(); } try { FileOutputStream fos=new FileOutputStream(photo.getPath()); fos.write(jpeg[0]); fos.close(); } catch ( java.io.IOException e) { Log.e("PictureDemo","Exception in photoCallback",e); } return (null); }
Example 55
From project cw-android, under directory /Fonts/FontSampler/src/com/commonsware/android/fonts/.
Source file: FontSampler.java

@Override public void onCreate(Bundle icicle){ super.onCreate(icicle); setContentView(R.layout.main); TextView tv=(TextView)findViewById(R.id.custom); Typeface face=Typeface.createFromAsset(getAssets(),"fonts/HandmadeTypewriter.ttf"); tv.setTypeface(face); File font=new File(Environment.getExternalStorageDirectory(),"MgOpenCosmeticaBold.ttf"); if (font.exists()) { tv=(TextView)findViewById(R.id.file); face=Typeface.createFromFile(font); tv.setTypeface(face); } else { findViewById(R.id.filerow).setVisibility(View.GONE); } }
Example 56
From project cw-omnibus, under directory /Camera/Content/src/com/commonsware/android/camcon/.
Source file: CameraContentDemoActivity.java

@Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File dir=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); output=new File(dir,"CameraContentDemo.jpeg"); i.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(output)); startActivityForResult(i,CONTENT_REQUEST); }
Example 57
From project daily-money, under directory /dailymoney/src/com/bottleworks/commons/util/.
Source file: Files.java

/** * Copy database files which include dm_master.db, dm.db and dm_<i>bookid<i>.db * @param sourceFolder source folder * @param targetFolder target folder * @param date Copy date. If date is not null, it will make another copy named with '.yyyyMMdd_HHmmss' as suffix. It is also used to identify copy from SD to DB when date is null * @return Number of files copied. * @throws IOException */ public static int copyDatabases(File sourceFolder,File targetFolder,Date date) throws IOException { int count=0; String state=Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state) && sourceFolder.exists() && targetFolder.exists()) { String[] filenames=sourceFolder.list(new FilenameFilter(){ @Override public boolean accept( File dir, String filename){ if (filename.startsWith("dm") && filename.endsWith(".db")) { return true; } return false; } } ); String bakDate=date == null ? null : backupDateFmt.format(date) + ".bak"; if (filenames != null && filenames.length != 0) { List<String> dbs=Arrays.asList(filenames); if (dbs.contains("dm_master.db") && dbs.contains("dm.db")) { for ( String db : dbs) { Files.copyFileTo(new File(sourceFolder,db),new File(targetFolder,db)); count++; if (bakDate != null) { Files.copyFileTo(new File(sourceFolder,db),new File(targetFolder,db + "." + bakDate)); } } } } } return count; }
Example 58
From project danbo, under directory /src/us/donmai/danbooru/danbo/activity/.
Source file: HomeActivity.java

private boolean checkPhoneStatus(){ NetworkState ns=new NetworkState(this); if (!ns.connectionAvailable()) { Log.d("danbo","No connection available"); AlertDialog.Builder alertBuilder=new AlertDialog.Builder(this); alertBuilder.setMessage(R.string.error_no_connection_available); alertBuilder.setNegativeButton(R.string.button_exit,new DialogInterface.OnClickListener(){ public void onClick( DialogInterface arg0, int arg1){ HomeActivity.this.finish(); } } ); AlertDialog networkAlert=alertBuilder.create(); networkAlert.show(); return false; } String state=Environment.getExternalStorageState(); if (!(Environment.MEDIA_MOUNTED.equals(state))) { AlertDialog.Builder alertBuilder=new AlertDialog.Builder(this); alertBuilder.setMessage(R.string.error_sd_not_available); alertBuilder.setNegativeButton(R.string.button_exit,new DialogInterface.OnClickListener(){ public void onClick( DialogInterface arg0, int arg1){ HomeActivity.this.finish(); } } ); AlertDialog alert=alertBuilder.create(); alert.show(); return false; } return true; }
Example 59
From project Diktofon, under directory /app/src/kaljurand_at_gmail_dot_com/diktofon/.
Source file: Dirs.java

public static void setBaseDir(String packageName){ String baseDirAsString=Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + packageName+ "/files/"; sBaseDir=new File(baseDirAsString); sRecordingsDir=new File(baseDirAsString + RECORDINGS); sNomediaFile=new File(baseDirAsString + RECORDINGS + ".nomedia"); }
Example 60
From project DownloadProvider, under directory /src/com/mozillaonline/downloadprovider/.
Source file: DownloadProviderActivity.java

private void startDownload(){ String url=mUrlInputEditText.getText().toString(); Uri srcUri=Uri.parse(url); DownloadManager.Request request=new Request(srcUri); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,"/"); request.setDescription("Just for test"); mDownloadManager.enqueue(request); }
Example 61
From project dreamDroid, under directory /src/net/reichholf/dreamdroid/.
Source file: CustomExceptionHandler.java

/** * @return */ public long getAvailableInternalMemorySize(){ File path=Environment.getDataDirectory(); StatFs stat=new StatFs(path.getPath()); long blockSize=stat.getBlockSize(); long availableBlocks=stat.getAvailableBlocks(); return availableBlocks * blockSize; }
Example 62
From project droid-comic-viewer, under directory /src/net/robotmedia/acv/comic/.
Source file: Comic.java

protected File createTempFile(String name){ File dir=new File(Environment.getExternalStorageDirectory(),this.getRelativePath()); if (id != null) { dir=new File(dir,this.getID()); } dir.mkdirs(); if (name.contains(File.separator)) { String nameDir=name.substring(0,name.lastIndexOf(File.separator)); String nameFile=name.substring(name.lastIndexOf(File.separator) + 1); File f=new File(dir,nameDir); f.mkdirs(); return new File(f,nameFile); } else { return new File(dir,name); } }
Example 63
From project droid-fu, under directory /src/main/java/com/github/droidfu/cachefu/.
Source file: AbstractCache.java

/** * Enable caching to the phone's internal storage or SD card. * @param context the current context * @param storageDevice where to store the cached files, either {@link #DISK_CACHE_INTERNAL} or{@link #DISK_CACHE_SDCARD}) * @return */ public boolean enableDiskCache(Context context,int storageDevice){ Context appContext=context.getApplicationContext(); String rootDir=null; if (storageDevice == DISK_CACHE_SDCARD && Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { rootDir=Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + appContext.getPackageName()+ "/cache"; } else { File internalCacheDir=appContext.getCacheDir(); if (internalCacheDir == null) { return (isDiskCacheEnabled=false); } rootDir=internalCacheDir.getAbsolutePath(); } setRootDir(rootDir); File outFile=new File(diskCacheDirectory); if (outFile.mkdirs()) { File nomedia=new File(diskCacheDirectory,".nomedia"); try { nomedia.createNewFile(); } catch ( IOException e) { Log.e(LOG_TAG,"Failed creating .nomedia file"); } } isDiskCacheEnabled=outFile.exists(); if (!isDiskCacheEnabled) { Log.w(LOG_TAG,"Failed creating disk cache directory " + diskCacheDirectory); } else { Log.d(name,"enabled write through to " + diskCacheDirectory); Log.d(name,"sanitize DISK cache"); sanitizeDiskCache(); } return isDiskCacheEnabled; }