S
S
sfilmak2015-06-11 21:36:37
JavaScript
sfilmak, 2015-06-11 21:36:37

How to make an Android application automatically create a certain file on installation?

Hello.
There was a question. How can I make the application automatically create a certain file in a certain folder during installation? For example, sample.txt in the Android folder?
Thanks in advance! And sorry for the possibly stupid questions.
MainActivity:

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.text.method.LinkMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public class MainActivity extends ActionBarActivity {
    private final static String FILENAME = "sample.txt"; // имя файла
    private EditText mEditText;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        mEditText = (EditText) findViewById(R.id.editText);

        AdView mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

        TextView t2 = (TextView) findViewById(R.id.textView8);
        t2.setMovementMethod(LinkMovementMethod.getInstance());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_save:
                saveFile(FILENAME);
                return true;
            default:
                return true;
            case R.id.action_settings:
                Intent intent = new Intent();
                intent.setClass(this, SettingsActivity.class);
                startActivity(intent);
                return true;
            case R.id.plus:
                intent = new Intent();
                intent.setClass(this, PlusActivity.class);
                startActivity(intent);
                return true;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(this);
        // читаем установленное значение из CheckBoxPreference
        if (prefs.getBoolean(getString(R.string.pref_openmode), false)) {
            openFile(FILENAME);

            // читаем стили текста из ListPreference
            String regular = prefs.getString(getString(R.string.pref_style), "");
            int typeface = Typeface.NORMAL;

            if (regular.contains("Bold"))
                typeface += Typeface.BOLD;

            if (regular.contains("Italic"))
                typeface += Typeface.ITALIC;

// меняем настройки в EditText
            mEditText.setTypeface(null, typeface);
        }

    }

    // Метод для открытия файла
    private void openFile(String fileName) {
        try {
            InputStream inputStream = openFileInput(fileName);

            if (inputStream != null) {
                InputStreamReader isr = new InputStreamReader(inputStream);
                BufferedReader reader = new BufferedReader(isr);
                String line;
                StringBuilder builder = new StringBuilder();

                while ((line = reader.readLine()) != null) {
                    builder.append(line + "\n");
                }

                inputStream.close();
                mEditText.setText(builder.toString());
            }
        } catch (Throwable t) {
            Toast.makeText(getApplicationContext(),
                    "Exception: " + t.toString(), Toast.LENGTH_LONG).show();
        }
    }

    // Метод для сохранения файла
    private void saveFile(String fileName) {
        try {
            OutputStream outputStream = openFileOutput(fileName, 0);
            OutputStreamWriter osw = new OutputStreamWriter(outputStream);
            osw.write(mEditText.getText().toString());
            osw.close();
        } catch (Throwable t) {
            Toast.makeText(getApplicationContext(),
                    "Exception: " + t.toString(), Toast.LENGTH_LONG).show();
        }
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Konstantin Berkov, 2015-06-11
@konstantin_berkow

You can do it easier, without a receiver, for this you need to extend Application and specify a new class in the manifest, so in onCreate of your Application you can create a file and if it already existed, do nothing with it. True, when deleting, it is not a fact that the file will be deleted, so it may be worth storing the creation date in the internal storage of your program to verify that the file is recent.

D
drYOM, 2015-06-11
@drYOM

First you need to define a BroadcastReceiver that will respond to installation events, for this you can define the following intent-filter in the manifest:

<receiver android:name=".YourReceiver">
        <intent-filter>
            <action android:name="android.intent.action.PACKAGE_INSTALL" />
            <action android:name="android.intent.action.PACKAGE_ADDED" />
            <data android:scheme="package"/>
        </intent-filter>
</receiver>

Then you need to create a file in your BroadcastReceiver in the onReceive() method:
String content = "hello world";
String dir = Environment.getExternalStorageDirectory() + "/Android";
File file;
FileOutputStream outputStream;
try {
    file = new File(dir, "sample.txt");
    outputStream = new FileOutputStream(file);
    outputStream.write(content.getBytes());
    outputStream.close();
} catch (IOException e) {
    e.printStackTrace();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question