aboutsummaryrefslogtreecommitdiff
path: root/content/AutoBackupForApps/Application/src/main/java/com/example/android/autobackupsample/AddFileActivity.java
blob: 00cd1e35cbc61e1cfde0e4f81d133355aaf082e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.android.autobackupsample;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.android.autobackupsample.MainActivityFragment;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

/**
 * The purpose of AddFileActivity activity is to create a data file based on the
 * file name and size parameters specified as an Intent external parameters or with the
 * activity UI.
 * <p/>
 * The optional intent parameters are
 * {@link com.example.android.autobackupsample.AddFileActivity#FILE_NAME} and
 * {@link com.example.android.autobackupsample.AddFileActivity#FILE_SIZE_IN_BYTES}.
 * {@link com.example.android.autobackupsample.AddFileActivity#FILE_STORAGE}.
 * <p/>
 * The activity will return an
 * {@link com.example.android.autobackupsample.MainActivityFragment#ADD_FILE_RESULT_ERROR}
 * if intent parameters are specified incorrectly or it will display Toast messages to the user
 * if those parameters are specified via the activity UI.
 */
public class AddFileActivity extends Activity {

    private static final String TAG = "AutoBackupSample";

    /**
     * The intent parameter that specifies a file name. The file name must be unique for the
     * application internal directory.
     */
    public static final String FILE_NAME = "file_name";

    /**
     * The intent parameter that specifies a file size in bytes. The size must be a number
     * larger or equal to 0.
     */
    public static final String FILE_SIZE_IN_BYTES = "file_size_in_bytes";

    /**
     * The file storage is an optional parameter. It should be one of these:
     * "INTERNAL", "EXTERNAL", "DONOTBACKUP". The default option is "INTERNAL".
     */
    public static final String FILE_STORAGE = "file_storage";

    /**
     * A file size multiplier. It is used to calculate the total number of bytes to be added
     * to the file.
     */
    private int mSizeMultiplier = 1;

    /**
     * Defines File Storage options.
     */
    private static enum FileStorage {
        INTERNAL,
        EXTERNAL,
        DONOTBACKUP;
    }

    /**
     * Contains a selected by a user file storage option.
     */
    private FileStorage mFileStorage = FileStorage.INTERNAL;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_file);
        initFileSizeSpinner();
        initFileStorageSpinner();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // If an intent has extra parameters, create the file and finish the activity.
        if (getIntent().hasExtra(FILE_NAME) && getIntent().hasExtra(FILE_SIZE_IN_BYTES)) {
            String fileName = getIntent().getStringExtra(FILE_NAME);
            String sizeInBytesParamValue = getIntent().getStringExtra(FILE_SIZE_IN_BYTES);
            String fileStorageParamValue = FileStorage.INTERNAL.toString();

            if (getIntent().hasExtra(FILE_STORAGE)) {
                fileStorageParamValue = getIntent().getStringExtra(FILE_STORAGE);
            }

            if (TextUtils.isEmpty(fileName) ||
                    isFileExists(fileName) ||
                    !isSizeValid(sizeInBytesParamValue) ||
                    !isFileStorageParamValid(fileStorageParamValue)) {
                setResult(MainActivityFragment.ADD_FILE_RESULT_ERROR);
                finish();
                return;
            }

            mFileStorage = FileStorage.valueOf(fileStorageParamValue);

            if (mFileStorage == FileStorage.EXTERNAL && !Utils.isExternalStorageAvailable()) {
                setResult(MainActivityFragment.ADD_FILE_RESULT_ERROR);
                finish();
                return;
            }

            createFileWithRandomDataAndFinishActivity(fileName, mFileStorage,
                    sizeInBytesParamValue);
        }
    }

    /**
     * A handler function for a Create File button click event.
     *
     * @param view a reference to the Create File button view.
     */
    public void onCreateFileButtonClick(View view) {
        EditText fileNameEditText = (EditText) findViewById(R.id.file_name);
        EditText fileSizeEditText = (EditText) findViewById(R.id.file_size);
        String fileName = fileNameEditText.getText().toString();
        String fileSizeEditTextValue = fileSizeEditText.getText().toString();

        if (TextUtils.isEmpty(fileName) || isFileExists(fileName)) {
            Toast toast = Toast.makeText(this, getText(R.string.file_exists), Toast.LENGTH_LONG);
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.show();
            return;
        }

        if (!isSizeValid(fileSizeEditTextValue)) {
            Toast toast = Toast.makeText(this, getText(R.string.file_size_is_invalid),
                    Toast.LENGTH_LONG);
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.show();
            return;
        }

        long fileSize = Integer.valueOf(fileSizeEditTextValue) * mSizeMultiplier;

        if (mFileStorage == FileStorage.EXTERNAL && !Utils.isExternalStorageAvailable()) {
            Toast toast = Toast.makeText(this,
                    getText(R.string.external_storage_unavailable), Toast.LENGTH_LONG);
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.show();
            return;
        }

        createFileWithRandomDataAndFinishActivity(fileName, mFileStorage, String.valueOf(fileSize));
    }

    private void initFileSizeSpinner() {
        Spinner spinner = (Spinner) findViewById(R.id.file_size_spinner);
        final ArrayAdapter<CharSequence> adapter =
                ArrayAdapter.createFromResource(this, R.array.file_size_array,
                        android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String sizeMeasure = adapter.getItem(position).toString();
                mSizeMultiplier = (int) Math.pow(1024, position);
                if (Log.isLoggable(TAG, Log.DEBUG)) {
                    Log.d(TAG, String.format("Selected: %s, %d", sizeMeasure,
                            mSizeMultiplier));
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void initFileStorageSpinner() {
        Spinner spinner = (Spinner) findViewById(R.id.storage_spinner);
        final ArrayAdapter<CharSequence> adapter =
                ArrayAdapter.createFromResource(this, R.array.file_storage_array,
                        android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mFileStorage = FileStorage.values()[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void createFileWithRandomDataAndFinishActivity(String fileName, FileStorage storage,
                                                           String sizeInBytes) {
        long size = Long.valueOf(sizeInBytes);
        File file = null;
        FileOutputStream out = null;
        BufferedOutputStream bufOut = null;
        try {
            switch (storage) {
                case INTERNAL:
                    file = getInternalFile(fileName);
                    out = openFileOutput(file.getName(), Context.MODE_PRIVATE);
                    break;
                case EXTERNAL:
                    assert Utils.isExternalStorageAvailable() :
                            "The external storage is not available";
                    File externalAppDir = getExternalFilesDir(null);
                    file = new File(externalAppDir, fileName);
                    out = new FileOutputStream(file);
                    break;
                case DONOTBACKUP:
                    file = new File(getNoBackupFilesDir(), fileName);
                    out = new FileOutputStream(file);
                    break;
            }

            if (file == null || out == null) {
                Log.d(TAG, "Unable to create file output stream");
                // Returning back to the caller activity.
                setResult(MainActivityFragment.ADD_FILE_RESULT_ERROR);
                finish();
                return;
            }

            bufOut = new BufferedOutputStream(out);
            for (int i = 0; i < size; i++) {
                byte b = (byte) (255 * Math.random());
                bufOut.write(b);
            }

            String message = String.format("File created: %s, size: %s bytes",
                    file.getAbsolutePath(), sizeInBytes);

            Toast toast = Toast.makeText(this, message, Toast.LENGTH_LONG);
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.show();
            Log.d(TAG, message);

            // Returning back to the caller activity.
            setResult(MainActivityFragment.ADD_FILE_RESULT_SUCCESS);
            finish();
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
            // Returning back to the caller activity.
            setResult(MainActivityFragment.ADD_FILE_RESULT_ERROR);
            finish();
        } finally {
            if (bufOut != null) {
                try {
                    bufOut.close();
                } catch (Exception e) {
                    // Ignore.
                }
            }
        }
    }

    private boolean isFileExists(String fileName) {
        File file = getInternalFile(fileName);
        if (file.exists()) {
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, "This file exists: " + file.getName());
            }
            return true;
        }
        return false;
    }

    private boolean isSizeValid(String sizeInBytesParamValue) {
        long sizeInBytes = 0;
        try {
            sizeInBytes = Long.valueOf(sizeInBytesParamValue);
        } catch (NumberFormatException e) {
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, "Invalid file size: " + sizeInBytesParamValue);
            }
            return false;
        }

        // Validate file size value. It should be 0 or a positive number.
        if (sizeInBytes < 0) {
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, "Invalid file size: " + sizeInBytes);
            }
            return false;
        }
        return true;
    }

    private boolean isFileStorageParamValid(String fileStorage) {
        try {
            mFileStorage = FileStorage.valueOf(fileStorage);
        } catch (IllegalArgumentException e) {
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, "Invalid file storage: " + fileStorage);
            }
            return false;
        }
        return true;
    }

    private File getInternalFile(String fileName) {
        File internalAppDir = getFilesDir();
        return new File(internalAppDir, fileName);
    }

}