Home > OS >  Bitmap PNG not fully saved in onPause
Bitmap PNG not fully saved in onPause

Time:07-27

I am developing a coloring book. And I want the state of the drawing to be saved when the user exits the application or changes the screen orientation.

My method works correctly when I set it to a button.

But when I add it to onPause it saves only part of the image.

I have already added execution of it in a separate thread, but this does not help either.

Here is my method:

private void setSavedBitmap(Bitmap finalBitmap) {

    file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "savedBitmap1.png");

    new Thread(new Runnable() {
        public void run() {
            try {
                FileOutputStream fos = null;
                    fos = new FileOutputStream(file);
                    finalBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                    if (fos != null) fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            };
        }
    }).start();

    SharedPreferencesFactory.saveString(this, "savedBitmap1", file.getPath());
}

onPause:

@Override
protected void onPause() {
    super.onPause();
    setSaveColor();
    setSavedBitmap(colourImageView.getmBitmap());
}

on button:

save.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        setSavedBitmap(colourImageView.getmBitmap());
        Toast.makeText(ColoringActivity.this, "You state image was saved",
                Toast.LENGTH_LONG).show();
    }
});

CodePudding user response:

Consider once you exit the application, the entire process will be killed so the thread execution stops. Using threads is not a good idea for background work. You could use Service or Workmanager to accomplish the work after the application is stopped.

CodePudding user response:

Thread will not survive after your app is kill i.e process is killed. So you need to use some kind of background execution framework Like a Service.

But normal Service has background limitations so it will also get killed so it has to be a foreground Service . the other option IntentService is deprecated .

you can use JobIntentService to save the bitmap. but it does not guarantees immediate execution which in your case is mandatory See This thread. On other hand WorkManger works in same way .

So conclusion here is use a Foreground Service to save the Bitmap . This will work well for your Usecase.

CodePudding user response:

It is always recommended to do this type of operation in the background thread. You can achieve this in multiple ways such as:

  • Work Manager (Best Choice)
  • Intent Service
  • Job Scheduler
  • Related