在应用程序安装时复制SD卡上的文本文件?

3
我正在开发一款安卓游戏。我想在用户第一次安装游戏时将一个文本文件复制到外部SD卡中。该文本文件对于游戏的正常运行非常重要。
我应该如何做呢?我应该把文本文件放在Eclipse源代码项目的哪个位置,以便在构建APK文件时,我的文本文件也被捆绑在其中,当用户从该APK文件安装应用程序时,文本文件会被复制到“SDcard\data”文件夹中?
我应该写什么代码,以及在哪里编写代码,以便它只在安装时执行一次。
提前感谢您的帮助。

1
我认为假设用户一定有SD卡是不公平的。这并非运行Android所必需的。 - user457586
好的,假设我已经使用getExternalStorageState()检查了SD卡,并且它是存在的。 - Pargat
你不能在安装时执行代码。你的第一次机会是在应用程序首次启动时。 - FoamyGuy
@Tim 我知道我们不能在安装时运行代码。实际上,我指的是在第一次运行时。 - Pargat
5个回答

6
这是我在应用程序首次安装时将文件复制到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卡中创建该文件。 - Pargat
请发布您的代码使用情况和LogCat。我在我的应用程序中使用它没有问题-您只需要添加您的信息即可。 - user742030
嗨,我已经把它弄好了...之前犯了一个愚蠢的错误。非常感谢你,伙计... :) - Pargat

0

根据链接

有一个ACTION_PACKAGE_ADDED广播意图,但是正在安装的应用程序不会接收到此广播。

因此,使用SharedPreferences似乎是最简单的方法...

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

0

对于这个目标,最好的方法是使用SharedPreferences或将您的文件添加到Android项目中的“assets”目录中。


0
将文件放入资产文件夹中。然后,使用您想到的任何逻辑,在应用程序启动时确定是否是应用程序的第一次运行。
如果是第一次运行,您可以使用Activity中的getAssets()访问资产文件,并将其复制到必要的位置。

0

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

为了进行潜在的应用程序升级,您应该在文件中放置一个版本号,并进行检查。

如果您希望让高级用户手动编辑文件(以更改专家选项),则在升级时可能需要处理一些具有挑战性的情况。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接