Android internal storage with external storage

Source: Internet
Author: User
<span id="Label3"></p>Stored internally or externally<p><p><span style="color: #ff0000;">all Android devices have two file storage areas: "internal" and "external". </span>These two names came from the previous Android system, when most devices were built with immutable (internal Storage) and a removable Storage unit (external Storage) <span style="color: #00ff00;">similar to</span> the SD Card. After some devices have "internal" and "external" are made of non-unloaded built-in storage, although this whole block is <span style="color: #00ff00;">logically</span> divided into "internal" and "external", It is only now no longer distinguishable by whether or not it can be uninstalled. The difference between the two is listed Below:</p></p> <ul> <ul> <li><p><strong>Internal storage:</strong></p> <ul> <li>is always available</li> <li>The files here are <strong>only accessible by our app. </strong></li> <li>When the user uninstalls the app, the system will clean up the files that are related to the app in Internal.</li> <li>Internal is the best storage area we want to ensure is not accessed by users and other Apps.</li> </ul></li> <li><p><strong>External storage:</strong></p> <ul> <li>This could be a removable storage medium (such as an SD card) or a fixed internal storage for a PHONE.</li> <li>is not always available, because users sometimes mount external memory through USB storage mode, and when you remove this part of the mount, you cannot access it.</li> <li><strong>Everyone can access the file, so the files saved here may be accessed by other Programs. Files saved to the external storage are public and can be modified by the User.</strong></li> <li>When the user uninstalls our app, the system only deletes the relevant files under the external private directory (getexternalfilesdir ()).</li> <li>External is the best storage area where you don't need strict access rights and want these files to be shared by other apps or to allow users to access them from your computer.</li> </ul></li> </ul> </ul> <blockquote> <blockquote> <p><strong>Tip:</strong> Although the app is installed to internal storage by default, we can specify that the program is installed to external by declaring the Android:installlocation property in the Program's manifest File. Storage When a Program's installation file is large and the User's external storage space is greater than internal storage, the user will prefer to install the program to external Storage. See the app install location for more installation Information.</p> </blockquote> </blockquote>Get permission to external storage<p><p>In order to write data to EXTERNAL storage, You must request Write_external_storage permissions in your manifest File.</p></p><p><p>For internal storage, We do not need to declare any permissions, because the program defaults to read and write files in the program directory Permissions.</p></p><p><p></p></p>Save to internal Storage<p><p>When saving a file to internal storage, you can obtain the appropriate directory as a file object by performing one of the following two methods:</p></p> <ul> <ul> <li>Getfilesdir (): Returns a file representing the internal directory of our app.</li> <li>Getcachedir (): Returns a file that represents the internal cache directory for our app. Make sure that the files in this directory are deleted as soon as they are no longer needed and are reasonably limited in size, such as 1MB. When the system has insufficient internal storage space, it chooses to delete the cache file Itself.</li> </ul> </ul><p><p>You can use the file () Builder to create a new file under those directories, as Follows:</p></p><pre><pre><code class="lang-java"><span class="hljs-keyword">new File(context.getFilesDir(), filename);</span></code></pre></pre><p><p>similarly, You can also perform openfileoutput () to get a fileoutputstream for writing files to the internal directory. As follows:</p></p><pre><pre><code class="lang-java"><span class="hljs-string">"myfile";String string = <span class="hljs-string">"Hello world!";FileOutputStream outputStream;<span class="hljs-keyword">try { outputStream = openFileOutput(filename, Context.MODE_PRIVATE); outputStream.write(string.getBytes()); outputStream.close();} <span class="hljs-keyword">catch (Exception e) { e.printStackTrace();}</span></span></span></span></code></pre></pre><p><p>If you need to cache some files, you can use Createtempfile (). For example, The following method extracts a filename from the URL and then creates a file named after the file name in the Program's internal cache directory.</p></p><pre><pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public File <span class="hljs-title">getTempFile<span class="hljs-params">(Context context, String url) { File file; <span class="hljs-keyword">try { String fileName = Uri.parse(url).getLastPathSegment(); file = File.createTempFile(fileName, <span class="hljs-keyword">null, context.getCacheDir()); <span class="hljs-keyword">catch (IOException e) { <span class="hljs-comment">// Error while creating file } <span class="hljs-keyword">return file;}</span></span></span></span></span></span></span></span></span></code></pre></pre> <blockquote> <blockquote> <p><strong>note:</strong> The <strong>internal storage</strong> Directory of our app is stored in a specific directory of the Android file system as the App's package name <span style="color: #ff6600;"><strong>[data/data/com.example.xx] </strong></span>. technically, If the file is set to be readable, then other apps can read the internal File. however, other apps need to know the package name and file Name. If not set to be readable or writable, there is no way for other apps to read and Write. So as long as we use mode_private, these files cannot be accessed by other apps.</p> </blockquote> </blockquote>Save file to external Storage<p><p><span style="line-height: 1.5;">because external storage may be unavailable, such as when an SD card is Unplugged. therefore, the availability of the check should be checked before access. We can </span> <span style="line-height: 1.5;">query the state of external storage by executing getexternalstoragestate (). If the return status is</span> media_mounted<span style="line-height: 1.5;">, you can read and Write. Examples are as follows:</span></p></p><pre><code class="lang-java"> <span class="hljs-comment">/* Checks If external storage is available for read and write */<span class="hljs-function"><span class="hljs-keyword">Public<span class="hljs-keyword">Boolean<span class="hljs-title">Isexternalstoragewritable<span class="hljs-params">() {String state = Environment.getexternalstoragestate ();<span class="hljs-keyword"><span class="hljs-keyword">if (Environment.MEDIA_MOUNTED.equals (state)) {<span class="hljs-keyword">return <span class="hljs-keyword">true; } <span class="hljs-keyword">return <span class="hljs-keyword">false;} <span class="hljs-comment">/* Checks If external storage is available-at least read */<span class="hljs-function"> <spa n class="hljs-keyword"> public <span class="hljs-keyword">boolean <span class="hljs-title"> Isexternalstoragereadable<span class="hljs-params"> () {String state = Environment.getexternalstoragestate (); <span class="hljs-keyword">if (Environment.MEDIA_MOUNTED.equals (state) | | Environment.MEDIA_MOUNTED_READ_ONLY.equals (state)) {<span class="hljs-keyword">return <span class="hljs-keyword">true;} <span class="hljs-keyword">return <span class="hljs-keyword">false;} <br> <br> <span style="font-size:14px;"> files in external storage can be modified by users or other applications, and there are two types of files (or directories): </span> <br> </span> </span> </span></span></span></span></span></span> </spa></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></pre> <ul> <ul> <li><strong>Public Files (common external Storage)</strong> : These files are publicly for users and other apps, and these files should be retained when the user uninstalls our app. For example, images that were taken by our app, videos, or downloaded Files.</li> <li>private <strong>files (proprietary External storage)</strong>: These files are completely private to our app and should be deleted when the app is Uninstalled. Although these files are technically accessible to users and other apps because they are stored in external storage, those files are actually meaningless to other apps. therefore, when the user uninstalls our app, the system deletes the private directory under it. For example, Those cached files that were downloaded by our app.</li> </ul> </ul><p><p>to <span style="color: #ff6600;">Save the file as public in the external storage, use the <span style="color: #ff6600;">getexternalstoragepublicdirectory ()</span> method to get one file Object. These files should be retained when the user uninstalls our app. </span>This method requires a specific parameter to specify the file types of the public for easy organization with other public files, such as Directory_music or Directory_pictures. For example:</p></p><pre><pre> <code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public File <span class="hljs-title">getalbumstoragedir<span class="hljs-params"> (String Albumname) { <span class="hljs-comment">//Get The directory for the User's public pictures directory. File File = <span class="hljs-keyword">new file (environment.getexternalstoragepublicdirectory ( environment.directory_pictures), albumname); <span class="hljs-keyword">if (!file.mkdirs ()) {log.e (log_tag, <span class="hljs-string"> "Directory not created");} <span class="hljs-keyword">return file;} </span> </span> </span> </span> </span> </span> </span> </span> </span> </code> </pre></pre><p><p> <span style="color: #ff6600;" to save the file as private in external storage, you can do <span getexternalfilesdir () < span>   to get the appropriate directory and pass a parameter indicating the file Type. </span> each of the directory created This's added to a parent directory, the encapsulates all your app ' s external storage fi les, which the system deletes when the user uninstalls your app. The following example: </p></p><pre><pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public File <span class="hljs-title">getAlbumStorageDir<span class="hljs-params">(Context context, String albumName) { <span class="hljs-comment">// Get the directory for the app‘s private pictures directory. File file = <span class="hljs-keyword">new File(context.getExternalFilesDir( Environment.DIRECTORY_PICTURES), albumName); <span class="hljs-keyword">if (!file.mkdirs()) { Log.e(LOG_TAG, <span class="hljs-string">"Directory not created"); } <span class="hljs-keyword">return file;}</span></span></span></span></span></span></span></span></span></code></pre></pre><p><p>If at first, there are no predefined subdirectories to hold our files, you can pass them in the Getexternalfilesdir () method <code>null</code> . It returns the root directory of the App's private under external storage.</p></p><p><p><span style="color: #ff6600;">Keep in mind that the directory created by the Getexternalfilesdir () method is deleted by the system when the app is Uninstalled. If our files want to remain when the app is deleted, use Getexternalstoragepublicdirectory ().</span></p></p><p><p>Whether using getexternalstoragepublicdirectory () to store files that can be shared, or using Getexternalfilesdir () to store files that are private to our app, it's important to That's The constant that's going to use those similar <code>DIRECTORY_PICTURES</code> Apis. Those directory type parameters can ensure that those files are treated correctly by the System. For example, files that are <code>DIRECTORY_RINGTONES</code> saved by type will be considered by the System's media scanner as ringtone rather than music.</p></p><p><p><strong><span style="color: #ff6600;">Note: If you store your images or videos in a directory (app Private) provided by Getexternalfilesdir (), Media scanner (scanner) cannot access your files because they are private to your app.</span></strong></p></p><p><p></p></p>Query the remaining space<p><p>If you know the size of the file you want to save beforehand, you can avoid ioexception by executing getfreespace () or gettotalspace () to determine if there is enough space to save the File. Those methods provide the currently available space and the total capacity of the storage System.</p></p><p><p>however, the system does not guarantee that you can write to <code>getFreeSpace()</code> the capacity file through the query, if the remaining capacity of the query is more than our file size mb, or the file system usage is less than 90%, so you can continue to write operations, otherwise it is best not to write IN.</p></p> <blockquote> <blockquote> <p><strong>note:</strong> There is no mandatory requirement to check the remaining capacity before writing the File. We can try to write the action first and then capture the Ioexception. This is only appropriate if you don't know the exact size of the file you want to write in Advance. For example, If you convert a PNG image to jpeg, we don't know what the resulting image size is.</p> </blockquote> </blockquote>deleting files<p><p>It should be deleted when you do not need to use certain files. The most straightforward way to delete a file is by directly executing the file <code>delete()</code> .</p></p><pre><pre><code class="lang-java">myFile.delete();</code></pre></pre><p><p>If the file is saved in internal storage, we can <code>Context</code> access it and delete it by execution <code>deleteFile()</code></p></p><pre><pre><code class="lang-java">myContext.deleteFile(fileName);</code></pre></pre> <blockquote> <blockquote> <p><strong>note:</strong> When the user uninstalls our app, the Android system will delete the following files:</p> <ul> <li>All files saved to internal Storage.</li> <li>All files saved in external storage using the Getexternalfilesdir () method.</li> </ul> <p>however, in general, we should <span style="color: #00ff00; background-color: #888888;">manually</span> delete all the cache files created by Getcachedir () and those that will not be used Again.</p> </blockquote> </blockquote><p><p>Android internal storage with external storage</p></p></span>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.