Environment Example

This example shows how to access the external public storage directory on a device.

A screenshot of the application.

We begin by declaring a unique namespace for the package we are creating. This is typically based on the reversed form of a domain name and should be unique to this package.

__package__ = "com.example.environment"

We import the classes and modules needed by our application. The most relevant class to this example is the Environment class which we use to access information about the application's environment.

from android.app import Activity
from android.os import Bundle, Environment
from android.view import ViewGroup
from android.widget import LinearLayout, TextView

The EnvironmentActivity class is derived from the standard Activity class and represents the application. Android will create an instance of this class when the user runs it.

class EnvironmentActivity(Activity):

    def __init__(self):

The initialisation method simply calls the corresponding method in the base class.

The onCreate method is called when the activity is created. We call the onCreate method of the base class with the Bundle object passed to this method to set up the application.

    def onCreate(self, bundle):
        Activity.onCreate(self, bundle)

We create a vertical layout to show a series of text labels.

        layout = LinearLayout(self)

We obtain a string constant that represents the "DCIM" subdirectory of the external public storage directory, and we add a text view with this string.

        t = Environment.DIRECTORY_DCIM
        view = TextView(self)

We pass the string constant to a static method of the Environment class to obtain the directory it refers to, and we add a text view with the path to its location.

        picturesDir = Environment.getExternalStoragePublicDirectory(t)
        fileNameView = TextView(self)

The files in the directory are obtained using its list method. Instead of creating a TextView for each file in the directory, we simply create a string with each file name on a line of its own, and we display it in a single TextView.

        files = picturesDir.list()
        s = ""
        i = 0
        while i < len(files):
            s = s.concat(files[i]).concat("\n")
            i += 1
        filesView = TextView(self)

Finally, we set the layout to be the main content of the activity.