Android Internal and External Storage Step by step Implementation and Top 10 Questions and Answers
 .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    Last Update: April 01, 2025      19 mins read      Difficulty-Level: beginner

Android Internal and External Storage: Explanation and Important Information

Android devices, like all modern smartphones, use different types of storage to manage data efficiently. The primary categories of storage are internal storage and external storage, each with distinct characteristics, use cases, and implications for both developers and users. Understanding these distinctions is crucial for creating apps that store data properly and ensure user experience.

1. Internal Storage

Definition: Internal storage refers to the memory built directly into an Android device, typically managed by the OS. This is essentially the non-removable storage area dedicated to running the system, applications, and storing app-specific data.

Key Features:

  • Private: By default, only the application that created a file can access it. It is protected through permission checks.
  • Limited: The available space is generally less than external storage. Developers must manage their app's data size wisely.
  • Automatic Backup: Files stored in internal storage can be backed up across devices using Google Drive, provided the app is configured for backup.
  • Speed: Generally faster than external storage because it’s directly attached to the CPU.

Common Use Cases:

  • App-Specific Resources: Storing application configurations, databases, and other resources that don’t need to be shared with other apps or the user.
  • Media Files: Temporary media assets used strictly within the app, such as cached images or audio files.
  • Private Data: Information that should not be accessible to other apps or the user, such as login credentials, keys, or sensitive documents.

Example Code for Writing to Internal Storage:

String filename = "myfile";
String string = "Hello world!";
FileOutputStream fos = openFileOutput(filename, MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

Example Code for Reading from Internal Storage:

String filename = "myfile";
InputStream fis = openFileInput(filename);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
    sb.append(line).append("\n");
}
String text = sb.toString();
bufferedReader.close();
isr.close();
fis.close();

Permissions: No permissions are required to write to app-specific internal storage. However, if the app needs to write to general internal storage (which is uncommon and not recommended), it requires WRITE_EXTERNAL_STORAGE permission.

2. External Storage

Definition: External storage can refer to removable storage devices (like microSD cards) or mounted volumes (such as USB drives). However, in the context of Android, it usually refers to secondary on-device storage, which can also be mounted as a USB mass storage device when connected to a PC.

Primary Types:

  • Primary External Storage: Directly integrated into the device but removable (on older devices).
  • Secondary External Storage: Removable microSD card (common in mid-range and lower-end devices).

Key Features:

  • Public: Files stored here are accessible globally by any other app and the user.
  • Capacity: Large capacity, ideal for hosting numerous user files such as images, videos, and documents.
  • Portability: Can be removed and used in other devices, enhancing portability of user files.
  • User Accessible: Users can easily browse and manage files stored on external storage using File managers, or via USB connection.
  • No Automatic Backup: Files stored on external storage are not automatically backed up by Google Drive.

Common Use Cases:

  • Media Files: User-generated content like photos, videos, and music.
  • Downloads: Files downloaded from the Internet, such as PDFs, APKs, etc.
  • Documents: Word documents, spreadsheets, and other productivity files.

Example Code for Writing to External Storage:

// Check if external storage is writable
if (!isExternalStorageWritable()) return;

// Create a File object in external storage
File file = new File(getExternalFilesDir(null), "sample.txt");

// Write to the file
try (FileOutputStream fos = new FileOutputStream(file)) {
    String stringToWrite = "Hello, world!";
    fos.write(stringToWrite.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
    Log.e("FileNotFoundException", e.getMessage());
}

// Method to check if external storage is writable
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    return Environment.MEDIA_MOUNTED.equals(state);
}

Example Code for Reading from External Storage:

// Check if external storage is readable
if (!isExternalStorageReadable()) return;

// Create a File object in external storage
File file = new File(getExternalFilesDir(null), "sample.txt");

StringBuilder textBuilder = new StringBuilder();

try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    String line;
    while ((line = br.readLine()) != null) {
        textBuilder.append(line);
        textBuilder.append('\n');
    }
} catch (IOException e) {
    Log.e("FileNotFoundException", e.getMessage());
}

String text = textBuilder.toString();
Log.d("FileContent", text);

// Method to check if external storage is readable
public boolean isExternalStorageReadable() {
    String state = Environment.getExternalStorageState();
    return Environment.MEDIA_MOUNTED.equals(state) ||
           Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
}

Permissions: Starting from Android 4.4 (KitKat), apps no longer need the READ_EXTERNAL_STORAGE permission to access files in their own private directories on external storage (getExternalFilesDir()). However, access to general public directories on external storage still requires READ_EXTERNAL_STORAGE and possibly WRITE_EXTERNAL_STORAGE for writing.

Important Considerations:

  • Media Mounted: Always check the availability of the external storage before reading or writing, as it can be ejected or made read-only.
  • Permissions: Properly request and handle runtime permissions for reading and writing, especially on newer Android versions (6.0 and above).
  • Storage Access Framework (SAF): Introduced in Android 4.4, SAF allows apps to access files on external storage without requiring READ_EXTERNAL_STORAGE permissions. This method involves asking the user to pick a file or directory and provides Uri-based access.
  • Performance: External storage can be slower than internal storage due to its indirect attachment to the CPU.

Summary

In summary, Android internal storage is private, limited, and automatically backed up, making it suitable for app-specific data. External storage offers larger capacity and user accessibility but lacks automatic backups and requires more careful handling to respect user privacy and data security. As a developer, choosing the right storage type is essential for creating efficient, user-friendly apps.

Understanding these nuances ensures optimal usage of storage resources, enhancing battery life, performance, and reliability, while providing users with a seamless experience. Both internal and external storage play critical roles in Android’s robust data management strategy.




Examples, Set Route and Run the Application: Android Internal and External Storage Step-by-Step Guide

Introduction

Understanding how to handle data storage in Android applications is essential for developers, as it enables the app to save user preferences, download files, or persist data across different sessions. Android provides two types of storage: internal storage and external storage. In this guide, we will cover both storage types, provide examples, set routes to these storages, and demonstrate running an application while walking through the data flow step-by-step.

Understanding Internal and External Storage

  1. Internal Storage

    • Private to the App: Data stored here can only be accessed by the app itself, ensuring privacy.
    • Automatic Management: Files are deleted when the app is uninstalled.
  2. External Storage

    • Shared with Other Apps & Users: Public storage area accessible by any app or user.
    • Persistent Even After Uninstallation: Data remains unless explicitly deleted by the user.

Setting Up Your Development Environment

Before diving into coding, ensure you have the following:

  • Android Studio Installed: Make sure it's up-to-date.
  • Android SDK: Ensure necessary SDK components are available, especially those related to storage permissions.
  • Device or Emulator: Choose a physical device or emulator for testing.

Example Scenario

Let’s create a simple app that writes text to both internal and external storage and displays it later.

Writing to Internal Storage

Step 1: Create Project

  1. Open Android Studio and create a new project (e.g., "StorageDemo").
  2. Choose "Empty Activity" template and proceed.

Step 2: Modify MainActivity.java

import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private static final String FILE_NAME = "example_file.txt";
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button buttonSaveInternal = findViewById(R.id.button_save_internal);
        Button buttonLoadInternal = findViewById(R.id.button_load_internal);
        textView = findViewById(R.id.text_view);

        buttonSaveInternal.setOnClickListener(v -> saveToInternalStorage());
        buttonLoadInternal.setOnClickListener(v -> loadFromInternalStorage());
    }

    private void saveToInternalStorage() {
        String content = "Hello, Internal Storage!";
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = openFileOutput(FILE_NAME, MODE_PRIVATE);
            fileOutputStream.write(content.getBytes());
            textView.setText("Saved to Internal Storage");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void loadFromInternalStorage() {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = openFileInput(FILE_NAME);
            int c;
            StringBuilder temp = new StringBuilder();
            while ((c = fileInputStream.read()) != -1) {
                temp.append((char) c);
            }
            textView.setText(temp.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Step 3: Update Layout (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <Button
        android:id="@+id/button_save_internal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save to Internal Storage" />

    <Button
        android:id="@+id/button_load_internal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Load from Internal Storage" />

    <TextView
        android:id="@+id/text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Content will appear here"
        android:paddingTop="16dp"/>
</LinearLayout>

Step 4: Testing

  1. Run the application on a device/emulator.
  2. Tap “Save to Internal Storage” — a file named example_file.txt is created within the internal storage.
  3. Tap “Load from Internal Storage” — the content from the file is displayed in the TextView.

Writing to External Storage

Writing to external storage requires permissions due to its public accessibility.

Step 1: Request Permissions

In the Android Manifest (AndroidManifest.xml):

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application
    ... >
    <!-- Required to request access to a scoped directory -->
    <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>
</application>

Create a new XML file in res/xml/file_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-files-path name="my_files" path="."/>
</paths>

Step 2: Modify MainActivity.java for External Storage

import android.Manifest;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private static final String FILE_NAME = "example_file.txt";
    private static final int REQUEST_CODE_PERMISSION = 100;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button buttonSaveExternal = findViewById(R.id.button_save_external);
        Button buttonLoadExternal = findViewById(R.id.button_load_external);
        textView = findViewById(R.id.text_view);

        buttonSaveExternal.setOnClickListener(v -> checkPermissionAndSaveToFile(true));
        buttonLoadExternal.setOnClickListener(v -> checkPermissionAndSaveToFile(false));
    }

    private void checkPermissionAndSaveToFile(boolean saveMode) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_CODE_PERMISSION);
        } else {
            if (saveMode) {
                saveToExternalStorage();
            } else {
                loadFromExternalStorage();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_PERMISSION) {
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                // Permission granted
            }
        }
    }

    private void saveToExternalStorage() {
        String content = "Hello, External Storage!";
        File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), FILE_NAME);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(content.getBytes());
            fos.close();
            textView.setText("Saved to External Storage");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void loadFromExternalStorage() {
        File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), FILE_NAME);
        StringBuilder stringBuilder = new StringBuilder();
        try {
            FileInputStream fis =  new FileInputStream(file);
            int i;
            while ((i = fis.read()) != -1)
                stringBuilder.append((char)i);
            fis.close();
            textView.setText(stringBuilder.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Step 3: Add Buttons to Layout (activity_main.xml)

<!-- Existing buttons -->
<Button
    android:id="@+id/button_save_external"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    android:text="Save to External Storage" />

<Button
    android:id="@+id/button_load_external"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Load from External Storage" />

Step 4: Testing

  1. Grant storage permissions when prompted.
  2. Tap “Save to External Storage” — the message is saved to Download/example_file.txt.
  3. Tap “Load from External Storage” — the content appears in TextView.

Data Flow Summary

  1. Internal Storage:

    • App writes data using openFileOutput() method.
    • Data is stored in /data/data/<app_package_name>/files/.
    • Accessible only by the app unless rooted.
  2. External Storage:

    • App requests write permission via Manifest and at runtime.
    • Data is typically stored in /storage/emulated/0/Android/data/<app_package_name>/files/Download/.
    • Shared among all apps but requires explicit permissions for write operations starting Android 6.0 (API level 23).

Conclusion

Handling both internal and external storage in Android requires understanding file operations and managing permissions appropriately, especially for newer Android versions. This guide provided practical examples, detailed steps, and explanations of each process to aid beginner developers in mastering Android storage handling.




Certainly! Here is a comprehensive "Top 10 Questions and Answers" guide on the topic of Android's internal and external storage:

Top 10 Questions and Answers on Android Internal and External Storage

1. What are the differences between Internal Storage and External Storage on Android?

  • Internal Storage: This type of storage is dedicated solely to the application that created it. The data is private to the app and other apps cannot access it unless they have the appropriate permissions, and even then only under specific conditions (like accessing shared user preferences). It's managed by the system, providing better security and no risk of media removal. Data stored here is automatically deleted when the app is uninstalled.
  • External Storage: This includes primary external storage (microSD cards and USB OTG) which isn't specific to any one application and can be used by any apps with the appropriate permissions. It's also accessible by the user through file managers and file sharing services. The main difference is that users can add, modify, or remove files from external storage as they wish, which poses a risk of data being lost or corrupted.

2. Is there a limit to the amount of storage an app can use on the device's Internal Storage?

  • Yes, each app has its own unique folder inside the device's internal storage and is limited to the space available in that folder, which varies based on the total memory available to the app. However, the Android system may enforce limits on the available space if necessary, such as reserving a portion for essential system files or apps.

3. How can an app access its files in Internal Storage?

  • Apps can access their files in internal storage using the Context object or methods provided by the File class. For example, to create a private file within the internal storage of your app, you could use getFilesDir() or getCacheDir(). Here's how you might do it:
    // Getting files directory
    File internalPath = getFilesDir(); 
    // Creating new file within internal storage
    File internalFile = new File(internalPath, fileName);
    

4. What is the recommended way for an app to write files to External Storage on Android?

  • When writing files to external storage, you should request the necessary permissions (WRITE_EXTERNAL_STORAGE) in the AndroidManifest.xml and handle runtime permission requests starting from Android 6.0 (API level 23). To write a file to the public external storage, you generally use Environment.getExternalStoragePublicDirectory(directoryType), where directoryType specifies the type of directory (e.g., DIRECTORY_MUSIC). Here’s an example:
    // Check if permission is granted or not
    if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions((Activity)context, 
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 
                REQUEST_CODE_WRITE_EXTERNAL_STORAGE);
    }
    
    // Writing a file
    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    File file = new File(path, fileName);
    try (FileOutputStream outputStream = new FileOutputStream(file)) {
        outputStream.write(content.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    }
    

5. Can Internal Storage be expanded or upgraded?

  • No, internal storage cannot be expanded or upgraded by the end-user. It is built into the device and its size is determined by the manufacturer at the time of manufacturing. However, some devices have options during the initial setup process to allocate certain sections of internal storage for expandable purposes like user data or app storage.

6. Are all files that are private to the app stored in Internal Storage?

  • Not necessarily. While most private app data is stored in internal storage, some data can be stored in a private area of the external storage as well. Files stored there are inaccessible to the general user and other apps unless those apps have the necessary permissions. This is particularly useful when dealing with large media files that do not fit into the internal storage.

7. What happens to files stored in Internal Storage versus External Storage when an app is uninstalled?

  • Files stored in the internal storage of an app are automatically deleted when that app is uninstalled. They are confined to the app's exclusive storage space. On the other hand, files stored in the external storage of the app remain intact after uninstallation unless they were placed in the app-specific directory (/Android/data/<app_package>), in which case, they would also be automatically deleted.

8. How does Android handle files in case an external SD card is removed?

  • If the external storage device such as an SD card is removed while the device is powered on, the system will send a MEDIA_REMOVED broadcast. This action prompts any apps that are currently performing operations on the external storage to stop those operations gracefully. Once the card is removed, all apps lose access to it until it is reinserted and properly mounted.

  • For Android apps, it’s important to check if the external storage state is available before attempting to read or write to it. You can do this by calling Environment.getExternalStorageState().

    String state = Environment.getExternalStorageState();
    if ( Environment.MEDIA_MOUNTED.equals(state) ) {
        // We can read and write the media
    } else if ( Environment.MEDIA_MOUNTED_READ_ONLY.equals(state) ) {
        // We can only read the media
    } else {
        // Something else is wrong. It may be one of many other states, but all we need
        // to know is we can neither read nor write
    }
    

9. What are the security considerations between Internal Storage and External Storage?

  • Internal Storage: Due to the encapsulated nature of internal storage, it provides better security. Data is more difficult for other applications to tamper with or access without explicit permissions. The system removes app data when uninstalled for added security.
  • External Storage: It’s more accessible to the user and other applications, leading to potential security risks. Malicious or poorly written applications can corrupt or delete files on external storage unless they are securely encrypted or stored in a well-controlled location. Also, external storage can be physically removed by the user, potentially exposing sensitive information.

10. How can I ensure that my application's data is preserved across OS updates and factory resets on Android?

  • While internal storage is cleared on a factory reset, apps can take steps to preserve important data:
    • Use cloud-based synchronization if feasible. This ensures that data is backed up to a remote server and can be restored if the app gets installed again.
    • Encrypt and store critical files on external storage. Although external storage is more accessible, making sure data is encrypted can provide a strong layer of protection.
    • Provide users with regular backups via options within your application. This allows them to maintain and restore important files manually.
    • In the case of OS upgrades, ensure that your app handles data migration appropriately. This involves updating data handling mechanisms to accommodate new versions of Android while ensuring no loss or corruption.

By understanding these fundamental differences and best practices, developers can make informed decisions about how to use storage effectively in Android applications, optimizing both performance and security.