Click here to Skip to main content
Click here to Skip to main content

Tagged as

Android Use Memory (Internal/External) And Intent To View Local HTML File In Browser

, 3 Dec 2012
Rate this:
Please Sign up or sign in to vote.
It is very simple article for opeaning html file in browser by using android intent and memory internal and external memory.

 

Introduction

Android provides several options for you to save persistent application data. The solution you choose depends on your specific needs, such as whether the data should be private to your application or accessible to other applications (and the user) and how much space your data requires. In this example we are using Intent, Internal Storage and External Storage.

About the Intent

Intent: An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.

Intent Structure: The primary pieces of information in an intent are:

  • action:The general action to be performed, such as ACTION_VIEW, ACTION_EDIT, ACTION_MAIN, etc.

  • data:The data to operate on, such as a person record in the contacts database, expressed as a URI.

Three of the core components of an application — activities, services, and broadcast receivers — are activated through messages, called intents. Intent messaging is a facility for late run-time binding between components in the same or different applications. The intent itself, an Intent object, is a passive data structure holding an abstract description of an operation to be performed — or, often in the case of broadcasts, a description of something that has happened and is being announced. There are separate mechanisms for delivering intents to each type of component:

  • An Intent object is passed to Context.startActivity() or Activity.startActivityForResult() to launch an activity or get an existing activity to do something new. (It can also be passed to Activity.setResult() to return information to the activity that called startActivityForResult().)
  • An Intent object is passed to Context.startService() to initiate a service or deliver new instructions to an ongoing service. Similarly, an intent can be passed to Context.bindService() to establish a connection between the calling component and a target service. It can optionally initiate the service if it's not already running.
  • Intent objects passed to any of the broadcast methods (such as Context.sendBroadcast(), Context.sendOrderedBroadcast(), or Context.sendStickyBroadcast()) are delivered to all interested broadcast receivers. Many kinds of broadcasts originate in system code.

About the Internal Storage

Internal Storage: Store private data on the device memory.

You can save files directly on the device's internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). When the user uninstalls your application, these files are removed.

To Write File: Call openFileOutput() with the name of the file and the operating mode. This returns a FileOutputStream. Write to the file with write().Close the stream with close().

MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to your application. Other modes available are: MODE_APPEND, MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE.

To Read File: Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream. Read bytes from the file with read().Then close the stream with close().

About the External Storage

External Storage: Store public data on the shared external storage.

Every Android-compatible device supports a shared "external storage" that you can use to save files. This can be a removable storage media (such as an SD card) or an internal (non-removable) storage. Files saved to the external storage are world-readable and can be modified by the user when they enable USB mass storage to transfer files on a computer.Writing to this path requires the WRITE_EXTERNAL_STORAGE permission

Checking Storage Availability

Before you do any work with the external storage, you should always call getExternalStorageState() to check whether the storage is available. This example checks whether the external storage is available to read and write. The getExternalStorageState() method returns other states that you might want to check, such as whether the media is being shared (connected to a computer), is missing entirely, has been removed badly, etc. You can use these to notify the user with more information when your application needs to access the media.

public boolean isSdReadable() {

    boolean mExternalStorageAvailable = false;
    try {
        String state = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(state)) {
            // We can read and write the media
            mExternalStorageAvailable = true;
            Log.i("isSdReadable", "External storage card is readable.");
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            // We can only read the media
            Log.i("isSdReadable", "External storage card is readable.");
            mExternalStorageAvailable = true;
        } 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
            mExternalStorageAvailable = false;
        }
    } catch (Exception ex) {

    }
    return mExternalStorageAvailable;
}

Code Part

Created four function for reading and writing. Function writeFileInternalStorage(), writeFileOnSDCard(), readSDCardFileOption(), and readInternalStorageOption().

Function readSDCardFileOption() to use read file from SD Card memory.In this function I have used file location directly which is "file:///sdcard/my.html". Call Intent service to open browser and load html file in browser from SD card memory.

Next function readInternalStorageOption() to use read file from internal memory.In this function I have used file location by calling method getApplication().getFilesDir().getAbsolutePath() then add file seprator and file name. Call Intent service to open browser and load html file in browser from internal memory.

public void readSDCardFileOption() {
    try {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setComponent(new ComponentName("com.android.browser",
                "com.android.browser.BrowserActivity"));
        intent.setDataAndType(Uri.parse("file:///sdcard/my.html"),
                "text/html");
        startActivity(intent);
    } catch (NullPointerException ex) {

    }
}

public void readInternalStorageOption() {
    try {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        String filePath = getApplication().getFilesDir().getAbsolutePath()
                + File.separator + "my.html";
        File f = new File(filePath);
        if (f.exists()) {
            Uri internal = Uri.fromFile(f);
            intent.setDataAndType(internal, "text/html");
        }
        startActivity(intent);
    } catch (NullPointerException ex) {

    }
}

Function writeFileInternalStorage() to use write file in internal memory. To access file by another application I have used property MODE_WORLD_READABLE.

public void writeFileInternalStorage() {

    String html = "<html>"
            + "<head>"
            + "<title>Internal HTML File</title>"
            + "<style type=\"text/css\">"
            + "body {margin:2px;#61210B;font-size:small;font-weight:normal;font-family:Arial;width:300px;}"
            + "h2{margin:5px;background-color:#184090;color:#ffffff;}"
            + "h3{margin:5px;color:#184090}"
            + "table{background-color:#ECEEF5;font-size:small;font-weight:normal;font-family:Arial;}"
            + "</style>"
            + "</head>"
            + "<body>"
            + "<table cellspacing=\"3\">"
            + "<tr><td><h2>Example for Internal Memory</h2></td></tr>"
            + "<tr><td><h3>Load HTML file from your Internal Memory</h3></td></tr>"
            + "<tr>" + "<td> Internal Memory data "+String.valueOf(iInternalCount)+" times." + "</td>"
            + "</tr>" + "</table>" + "</body></html>";

    try {
        String sfilename = "my.html";
        FileOutputStream fos = this.openFileOutput(sfilename,
                Context.MODE_PRIVATE | Context.MODE_WORLD_READABLE);
        fos.write(html.getBytes());
        fos.flush();
        fos.close();
        Toast.makeText(getBaseContext(),
                "Write file in external memory 'my.html'",
                Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
    }
}

Finally, function writeFileOnSDCard() to use write file in External memory (SD Card). To find memory status in Android phone I have used method isSdReadable(). Method isSdReadable() returns boolean value. If External Storage is available the value true will return else return true.

public void writeFileOnSDCard() {

    String html = "<html>"
            + "<head>"
            + "<title>External HTML File</title>"
            + "<style type=\"text/css\">"
            + "body {margin:2px;#61210B;font-size:small;font-weight:normal;font-family:Arial;width:300px;}"
            + "h2{margin:5px;background-color:#184090;color:#ffffff;}"
            + "h3{margin:5px;color:#184090}"
            + "table{background-color:#ECEEF5;font-size:small;font-weight:normal;font-family:Arial;}"
            + "</style>"
            + "</head>"
            + "<body>"
            + "<table cellspacing=\"3\">"
            + "<tr><td><h2>Example for SD Card</h2></td></tr>"
            + "<tr><td><h3>Load HTML file from your External Memory (SD Card)</h3></td></tr>"
            + "<tr>" + "<td> SD card data "+String.valueOf(iExternalCount)+" times." + "</td>" + "</tr>"
            + "</table>" + "</body></html>";

    try {
        if (isSdReadable()) {
            String fullPath = Environment.getExternalStorageDirectory()
                    .getAbsolutePath();
            File myFile = new File(fullPath + File.separator + "/my.html");

            FileOutputStream fOut = new FileOutputStream(myFile);
            OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
            myOutWriter.append(html);
            myOutWriter.close();
            fOut.close();
            Toast.makeText(getBaseContext(),
                    "Write file in internal memory 'my.html'",
                    Toast.LENGTH_SHORT).show();
        }

    } catch (Exception e) {
        Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT)
                .show();
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

R S Dodiya
Software Developer (Senior)
India India

Comments and Discussions

 
GeneralMy vote of 2 PinmemberAman Deep Arora4-Jun-13 19:58 
GeneralMy vote of 1 Pinmemberabollfazl4-Dec-12 7:55 
GeneralRe: My vote of 1 PinmemberProgramFOX22-Dec-12 6:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140827.1 | Last Updated 3 Dec 2012
Article Copyright 2012 by R S Dodiya
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid