[Android] When the application is reconnected, 'setup' operates again

When the application is reconnected, ‘setup’ operates again.

How to operate ‘SETUP’ only once?

void setup(){
    s1 = new MediaPlayer();
    s2 = new MediaPlayer();
    
    af1 = context.getAssets().openFd("1.mp3");
    af2 = context.getAssets().openFd("2.mp3");

    s1.setDataSource(af1.getFileDescriptor(), af1.getStartOffset(), af1.getLength());
    s2.setDataSource(af2.getFileDescriptor(), af2.getStartOffset(), af2.getLength());

    s1.prepare();
    s2.prepare();
}
  1. Run the created ‘APP’ on your smartphone. It works normally.

  2. It appears on the background screen for a while, then reconnects to the ‘APP’.

  3. ‘setup’ restarts, so it seems that mp3 files are duplicated twice in s1 and af1.

  4. The same sound source is played twice.

  5. Is there a way to prevent setup from working even after leaving the ‘APP’ screen?

boolean setup_en = true;
void setup(){

 if(setup_en){ setup_en = false;
    s1 = new MediaPlayer();
    s2 = new MediaPlayer();
    
    af1 = context.getAssets().openFd("1.mp3");
    af2 = context.getAssets().openFd("2.mp3");

    s1.setDataSource(af1.getFileDescriptor(), af1.getStartOffset(), af1.getLength());
    s2.setDataSource(af2.getFileDescriptor(), af2.getStartOffset(), af2.getLength());

    s1.prepare();
    s2.prepare();
  }
}

It can’t be solved with the above method, right?

1 Like

You could maybe handle it by saving to a random file during setup. This way you can check if the file exists. If it does then dont call the methods in setup.

Maybe theres a more elegant solution, or maybe you could make use of onload() and migrate the code from setup.

1 Like

@paulgoux

Thank you for your interest and reply.

  1. As you said, it’s a way to control through storage.
    I saved it in ‘.csv’ and processed it.

  2. The second is definitely to close the APP and turn it on again.

moveTaskToBack(true);
finishAndRemoveTask();
android.os.Process.killProcess(android.os.Process.myPid());

I solved it through the corresponding source code.

2 Likes