【问题标题】:Copy a text file on SD card at the time of application installation?在应用程序安装时复制 SD 卡上的文本文件?
【发布时间】:2012-06-20 14:27:35
【问题描述】:

我正在开发一款安卓游戏。我想在用户第一次安装游戏时将文本文件复制到外部 SD 卡。文本文件对于正确运行游戏很重要。

我该怎么做?我应该将文本文件放在 Eclipse 源项目中的哪个位置,以便在构建 apk 文件时,我的文本文件也被捆绑在其中,当用户从该 apk 文件安装应用程序时,文本文件被复制到“SDcard\data”文件夹.?

我应该编写什么代码以及在哪里编写,以便在安装时只执行一次。

提前致谢

【问题讨论】:

  • 我认为假设用户将拥有一张 SD 卡是不公平的。不需要运行 Android。
  • ok 假设我已经使用 getExternalStorageState() 检查了 sd 卡。它是存在的。
  • 安装时不能真正执行代码。您的第一次机会是您的应用程序第一次启动。
  • @Tim 我知道我们无法在安装时运行代码。实际上,安装时我的意思是第一次运行..

标签: android android-sdcard


【解决方案1】:

这是我在第一次安装应用程序时将文件复制到 sd 卡的方法:

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);
        }
    }

【讨论】:

  • 我收到了 SD 卡中文件的 FileNotFoundException。它没有在 sd 卡中创建文件。
  • 请发布您的代码使用情况和 LogCat。我在我的应用程序中使用它没有问题 - 您只需要添加您的信息
  • 嗨,我搞定了.. 犯了一个愚蠢的错误。非常感谢哥们... :)
【解决方案2】:

对于这个目标,最好的方法是创建 SharedPreferences 或者你的文件必须添加到 android 项目的“assets”目录中。

【讨论】:

    【解决方案3】:

    根据link

    有 ACTION_PACKAGE_ADDED 广播意图,but the application being installed doesn't receive this.

    所以看起来使用 SharedPreferences 是最简单的方法...

    SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(this);
    boolean firstRun = p.getBoolean(PREFERENCE_FIRST_RUN, true);
    p.edit().putBoolean(PREFERENCE_FIRST_RUN, false).commit();
    

    【讨论】:

      【解决方案4】:

      将文件放在资产文件夹中。然后,使用您想出的任何逻辑,在您的应用启动时确定它是否是应用的第一次运行。

      如果是,您可以使用 Activity 中的 getAssets() 来访问资产文件,然后将其复制到任何需要的地方。

      【讨论】:

        【解决方案5】:

        由于 sdcard 上的文件可能会被用户意外删除,因此您可能应该直接检查它的存在(并可能验证内容),而不是尝试使用独立的东西(例如共享首选项)来判断它是否存在是活动的第一次运行。

        出于潜在应用升级的目的,您可能应该在文件中输入一个版本号,并进行检查。

        如果您想让高级用户手动编辑该文件(以更改专家选项),那么您在升级时可能会遇到一些具有挑战性的情况。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-01-02
          • 2011-12-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多