onCreate
onCreate

Reputation: 775

Save file in main UI

I write a function, that save file to external storage:

public void saveBmp(Bitmap bmp) {
    File f = new File(Environment.getExternalStorageDirectory(), "test.jpg");
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(f);
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    }
    bmp.compress(CompressFormat.JPEG, 70, fos);
    try {
        fos.flush();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    bmp.recycle();
}

Why android not warning me, that i'm using file system in main UI. Is it right way or i need to use asynctask?

Upvotes: 2

Views: 1225

Answers (2)

Md. Arafat Al Mahmud
Md. Arafat Al Mahmud

Reputation: 3214

As per developer.android.com

*

The BitmapFactory.decode* methods, discussed in the Load Large Bitmaps Efficiently lesson, should not be executed on the main UI thread if the source data is read from disk or a network location (or really any source other than memory). The time this data takes to load is unpredictable and depends on a variety of factors (speed of reading from disk or network, size of image, power of CPU, etc.). If one of these tasks blocks the UI thread, the system flags your application as non-responsive and the user has the option of closing it (see Designing for Responsiveness for more information).

*

So what it suggests is you should not block the main UI thread by writing file to external storage. And it is strongle encouraged that you use AsyncTask

Upvotes: 3

Hitman
Hitman

Reputation: 598

You can create something like that. But I advise you to create and write in the file in an AsyncTask because if there are too many data to write in the file it will cost you a lot of seconds and in those seconds the user will not be able to do anything with your app because the main thread ( the UI thread ) is used to do the writing. Now it depends on how you designed your app. Maybe you don't want to let the user do anything else while the file is created, but even then I would say that you could do the writing in an AsyncTask, and while the writing is done you could display a Loading gif, or something to inform the user that the saving is in progress.

Upvotes: 1

Related Questions