3

I am working on an android game. I want to copy a text file to external SD card when the user installs the game for the first time. The text file is important for properly running the game.

How can I do that? Where should i place the text file in eclipse source project so that when i build the apk file, my text file also gets bundled in it and when a use installs application from that apk file the text file gets copied to "SDcard\data" folder.?

What code should i write and where, so that it gets executed only once at installation time.

Thanks in advance

Pargat
  • 769
  • 9
  • 23
  • 1
    I don't think it's fair to assume the user will have an SD card at all. It's not required to run Android. –  Jun 20 '12 at 14:30
  • ok assume that i have checked sd card using getExternalStorageState(). And it is present. – Pargat Jun 20 '12 at 14:33
  • You can't really execute code at installation time. Your first chance is the first time your application is launched. – FoamyGuy Jun 20 '12 at 15:47
  • @Tim I know we can't run code at installation. Actually by at installation i meant at first run.. – Pargat Jun 20 '12 at 20:45

5 Answers5

6

This is the methods I use to copy a file to the sd card when the app is first installed:

public class StartUp extends Activity {

    /**
     * -- Called when the activity is first created.
     * ==============================================================
     **/
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FirstRun();
    }

    private void FirstRun() {
        SharedPreferences settings = this.getSharedPreferences("YourAppName", 0);
        boolean firstrun = settings.getBoolean("firstrun", true);
        if (firstrun) { // Checks to see if we've ran the application b4
            SharedPreferences.Editor e = settings.edit();
            e.putBoolean("firstrun", false);
            e.commit();
            // If not, run these methods:
            SetDirectory();
            Intent home = new Intent(StartUp.this, MainActivity.class);
            startActivity(home);

        } else { // Otherwise start the application here:

            Intent home = new Intent(StartUp.this, MainActivity.class);
            startActivity(home);
        }
    }

/**
     * -- Check to see if the sdCard is mounted and create a directory w/in it
     * ========================================================================
     **/
    private void SetDirectory() {
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {

            extStorageDirectory = Environment.getExternalStorageDirectory().toString();

            File txtDirectory = new File(extStorageDirectory + "/yourAppName/txt/");
            // Create
            // a
            // File
            // object
            // for
            // the
            // parent
            // directory
            txtDirectory.mkdirs();// Have the object build the directory
            // structure, if needed.
            CopyAssets(); // Then run the method to copy the file.

        } else if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED_READ_ONLY)) {

            AlertsAndDialogs.sdCardMissing(this);//Or use your own method ie: Toast
        }

    }

    /**
     * -- Copy the file from the assets folder to the sdCard
     * ===========================================================
     **/
    private void CopyAssets() {
        AssetManager assetManager = getAssets();
        String[] files = null;
        try {
            files = assetManager.list("");
        } catch (IOException e) {
            Log.e("tag", e.getMessage());
        }
        for (int i = 0; i < files.length; i++) {
            InputStream in = null;
            OutputStream out = null;
            try {
                in = assetManager.open(files[i]);
                out = new FileOutputStream(extStorageDirectory + "/yourAppName/txt/" + files[i]);
                copyFile(in, out);
                in.close();
                in = null;
                out.flush();
                out.close();
                out = null;
            } catch (Exception e) {
                Log.e("tag", e.getMessage());
            }
        }
    }

    private void copyFile(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
    }
  • I am getting FileNotFoundException for the file in sd card. Its not creating the file in sd card. – Pargat Jun 20 '12 at 21:54
  • Plz post your code usage and the LogCat. I use this in my apps w/o issues - All you need is to add your info –  Jun 20 '12 at 22:02
  • Hi i got it work.. Was doing a silly mistake. Thanks a lot buddy... :) – Pargat Jun 20 '12 at 22:15
0

For this target the best way is make SharedPreferences or your file must be added in "assets" directory in android project.

Gorets
  • 2,434
  • 5
  • 27
  • 45
0

as per link

There is the ACTION_PACKAGE_ADDED Broadcast Intent, but the application being installed doesn't receive this.

So it looks using SharedPreferences is the easiest way...

SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(this);
boolean firstRun = p.getBoolean(PREFERENCE_FIRST_RUN, true);
p.edit().putBoolean(PREFERENCE_FIRST_RUN, false).commit();
Community
  • 1
  • 1
Dheeresh Singh
  • 15,643
  • 3
  • 38
  • 36
0

Put the file in the assets folder. Then, using whatever logic you come up with, when your app launches determine if it is the first run of the app.

If it is you can use getAssets() from an Activity to access the asset file and just copy it to wherever necessary.

barry
  • 4,037
  • 6
  • 41
  • 68
0

Since the file on the sdcard is something that could be accidentally deleted by the user, you should probably check directly for its presence (and possibly verify contents) rather than trying to use something independent such as a shared preference to tell if this is the first run of the activity.

For purposes of potential app upgrades, you should probably put a version number in the file, and check that.

If the file is something you want to let power users manually edit (to change expert options) then you may have a little bit of a challenging situation to handle on upgrade.

Chris Stratton
  • 39,853
  • 6
  • 84
  • 117