2 Activities Problem in Android Studio Code

0

I'm programming a little app via Android Studio. I'm working with 2 activities. My app stops responding as soon as my first activity opens the second one (When I'm running the app through the emulator). I realized that the problem first appeared as I inserted the for loop in my second activity. But the audio output of the notes is still done in the background.

Would be very nice if you could help me here.

Here the code:

public class MainActivity extends AppCompatActivity {
private Button myButton1, myButton2;
private EditText number;
TextView display;
int time = 0;
Bundle b;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    number = (EditText) findViewById(R.id.editTextNumber);
    myButton2 = (Button) findViewById(R.id.button);
    display = (TextView) findViewById(R.id.textView2);

    myButton2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String time = number.getText().toString();
            display.setText(time);
        }
    });


    myButton1 = (Button) findViewById(R.id.myButton);
    myButton1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            time = Integer.valueOf(number.getText().toString());
            open_activity2();
        }
    });
}

public void open_activity2() {
    Intent intent = new Intent(this, Activity2.class);
    intent.putExtra("Time", time);
    startActivity(intent);
}
}

Code to Activity2:

public class Activity2 extends AppCompatActivity {

private SoundPool soundPool;
private int sound1, sound2, sound3;
private Bundle b;
private int timeCycle;
private TextView displayNotes;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_2);

    displayNotes = (TextView) findViewById(R.id.textView);

    b = getIntent().getExtras();
    timeCycle = b.getInt("Time");

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .build();
        soundPool = new SoundPool.Builder()
                .setMaxStreams(5)
                .setAudioAttributes(audioAttributes)
                .build();
    } else {
        soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
    }
    sound1 = soundPool.load(this, R.raw.sound1, 1);
    sound2 = soundPool.load(this, R.raw.sound2, 1);
    sound3 = soundPool.load(this, R.raw.sound3, 1);

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    TimeUnit.SECONDS.sleep(timeCycle);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            randomNote();
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

        }
    }, 0);

}

protected void randomNote () {
    Random r = new Random();
    int randomNumber = r.nextInt(3);

    switch (randomNumber) {
        case 0:
            soundPool.play(sound1, 1, 1, 1, 0, 1);
            displayNotes.setText("Note: C");
            break;
        case 1:
            soundPool.play(sound2, 1, 1, 1, 0, 1);
            displayNotes.setText("Note: D");
            break;
        case 2:
            soundPool.play(sound3, 1, 1, 1, 0, 1);
            displayNotes.setText("Note: E");
            break;
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    soundPool.release();
    soundPool = null;
}

}

The error message I get, searched for something like XX and exception but didn't find anything:

11/12 15:20:46: Launching 'app' on No Devices.
Install successfully finished in 2 s 532 ms.
$ adb shell am start -n "com.example.noteswiktorapp/com.example.noteswiktorapp.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 7094 on device 'emulator-5554'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/.noteswiktorap: Not late-enabling -Xcheck:jni (already on)
I/.noteswiktorap: Unquickening 12 vdex files!
W/.noteswiktorap: Unexpected CPU variant for X86 using defaults: x86
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
W/.noteswiktorap: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
    Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
D/HostConnection: HostConnection::get() New Host Connection established 0xf1da78b0, tid 7117
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0 
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0xf1da6500: maj 3 min 0 rcv 3
D/EGL_emulation: eglMakeCurrent: 0xf1da6500: ver 3 0 (tinfo 0xf20f6050) (first time)
I/Gralloc4: mapper 4.x is not supported
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0xf1da6810, tid 7117
D/goldfish-address-space: allocate: Ask for block of size 0x100
    allocate: ioctl allocate returned offset 0x3fbe53000 size 0x2000
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0 
I/AssistStructure: Flattened final assist data: 1772 bytes, containing 1 windows, 11 views
D/CCodec: allocate(c2.android.mp3.decoder)
I/Codec2Client: Available Codec2 services: "software"
I/CCodec: Created component [c2.android.mp3.decoder]
D/CCodecConfig: read media type: audio/mpeg
D/ReflectedParamUpdater: extent() != 1 for single value type: algo.buffers.max-count.values
D/ReflectedParamUpdater: extent() != 1 for single value type: output.subscribed-indices.values
    extent() != 1 for single value type: input.buffers.allocator-ids.values
    extent() != 1 for single value type: output.buffers.allocator-ids.values
D/ReflectedParamUpdater: extent() != 1 for single value type: algo.buffers.allocator-ids.values
    extent() != 1 for single value type: output.buffers.pool-ids.values
    extent() != 1 for single value type: algo.buffers.pool-ids.values
I/CCodecConfig: query failed after returning 7 values (BAD_INDEX)
D/CCodecConfig: c2 config diff is Dict {
      c2::u32 coded.bitrate.value = 64000
      c2::u32 input.buffers.max-size.value = 8192
      c2::u32 input.delay.value = 0
      string input.media-type.value = "audio/mpeg"
      string output.media-type.value = "audio/raw"
      c2::u32 raw.channel-count.value = 2
      c2::u32 raw.sample-rate.value = 44100
    }
D/CCodec: [c2.android.mp3.decoder] buffers are bound to CCodec for this session
D/CCodecConfig: no c2 equivalents for durationUs
D/CCodecConfig: no c2 equivalents for track-id
    no c2 equivalents for encoder-delay
    no c2 equivalents for encoder-padding
    no c2 equivalents for flags
D/CCodecConfig: c2 config diff is   c2::u32 raw.channel-count.value = 1
      c2::u32 raw.sample-rate.value = 48000
W/Codec2Client: query -- param skipped: index = 1107298332.
D/CCodec: setup formats input: AMessage(what = 0x00000000) = {
      int32_t channel-count = 1
      int32_t max-input-size = 8192
      string mime = "audio/mpeg"
      int32_t sample-rate = 48000
    } and output: AMessage(what = 0x00000000) = {
      int32_t channel-count = 1
      string mime = "audio/raw"
      int32_t sample-rate = 48000
      int32_t encoder-delay = 528
      int32_t encoder-padding = 1848
    }
W/Codec2Client: query -- param skipped: index = 1342179345.
    query -- param skipped: index = 2415921170.
E/FMQ: grantorIdx must be less than 3
E/FMQ: grantorIdx must be less than 3
D/CCodecBufferChannel: [c2.android.mp3.decoder#769] Created input block pool with allocatorID 16 => poolID 17 - OK (0)
I/CCodecBufferChannel: [c2.android.mp3.decoder#769] Created output block pool with allocatorID 16 => poolID 26 - OK
D/CCodecBufferChannel: [c2.android.mp3.decoder#769] Configured output block pool ids 26 => OK
E/ion: ioctl c0044901 failed with code -1: Inappropriate ioctl for device
E/FMQ: grantorIdx must be less than 3
E/FMQ: grantorIdx must be less than 3
D/CCodecBufferChannel: [c2.android.mp3.decoder#769] MediaCodec discarded an unknown buffer
I/chatty: uid=10153(com.example.noteswiktorapp) NDK MediaCodec_ identical 1 line
D/CCodecBufferChannel: [c2.android.mp3.decoder#769] MediaCodec discarded an unknown buffer
I/hw-BpHwBinder: onLastStrongRef automatically unlinking death recipients
D/CCodec: allocate(c2.android.mp3.decoder)
I/CCodec: Created component [c2.android.mp3.decoder]
D/CCodecConfig: read media type: audio/mpeg
D/ReflectedParamUpdater: extent() != 1 for single value type: algo.buffers.max-count.values
D/ReflectedParamUpdater: extent() != 1 for single value type: output.subscribed-indices.values
D/ReflectedParamUpdater: extent() != 1 for single value type: input.buffers.allocator-ids.values
D/ReflectedParamUpdater: extent() != 1 for single value type: output.buffers.allocator-ids.values
D/ReflectedParamUpdater: extent() != 1 for single value type: algo.buffers.allocator-ids.values
    extent() != 1 for single value type: output.buffers.pool-ids.values
D/ReflectedParamUpdater: extent() != 1 for single value type: algo.buffers.pool-ids.values
I/CCodecConfig: query failed after returning 7 values (BAD_INDEX)
D/CCodecConfig: c2 config diff is Dict {
      c2::u32 coded.bitrate.value = 64000
      c2::u32 input.buffers.max-size.value = 8192
      c2::u32 input.delay.value = 0
      string input.media-type.value = "audio/mpeg"
      string output.media-type.value = "audio/raw"
      c2::u32 raw.channel-count.value = 2
      c2::u32 raw.sample-rate.value = 44100
    }
D/CCodec: [c2.android.mp3.decoder] buffers are bound to CCodec for this session
D/CCodecConfig: no c2 equivalents for durationUs
    no c2 equivalents for track-id
    no c2 equivalents for encoder-delay
    no c2 equivalents for encoder-padding
    no c2 equivalents for flags
D/CCodecConfig: c2 config diff is   c2::u32 raw.channel-count.value = 1
      c2::u32 raw.sample-rate.value = 48000
W/Codec2Client: query -- param skipped: index = 1107298332.
D/CCodec: setup formats input: AMessage(what = 0x00000000) = {
      int32_t channel-count = 1
      int32_t max-input-size = 8192
      string mime = "audio/mpeg"
      int32_t sample-rate = 48000
    } and output: AMessage(what = 0x00000000) = {
      int32_t channel-count = 1
      string mime = "audio/raw"
      int32_t sample-rate = 48000
      int32_t encoder-delay = 528
      int32_t encoder-padding = 1873
    }
W/Codec2Client: query -- param skipped: index = 1342179345.
    query -- param skipped: index = 2415921170.
E/FMQ: grantorIdx must be less than 3
    grantorIdx must be less than 3
D/CCodecBufferChannel: [c2.android.mp3.decoder#939] Created input block pool with allocatorID 16 => poolID 18 - OK (0)
I/CCodecBufferChannel: [c2.android.mp3.decoder#939] Created output block pool with allocatorID 16 => poolID 27 - OK
D/CCodecBufferChannel: [c2.android.mp3.decoder#939] Configured output block pool ids 27 => OK
E/FMQ: grantorIdx must be less than 3
E/FMQ: grantorIdx must be less than 3
D/CCodecBufferChannel: [c2.android.mp3.decoder#939] MediaCodec discarded an unknown buffer
I/chatty: uid=10153(com.example.noteswiktorapp) NDK MediaCodec_ identical 1 line
D/CCodecBufferChannel: [c2.android.mp3.decoder#939] MediaCodec discarded an unknown buffer
I/hw-BpHwBinder: onLastStrongRef automatically unlinking death recipients
D/CCodec: allocate(c2.android.mp3.decoder)
I/CCodec: Created component [c2.android.mp3.decoder]
D/CCodecConfig: read media type: audio/mpeg
D/ReflectedParamUpdater: extent() != 1 for single value type: algo.buffers.max-count.values
D/ReflectedParamUpdater: extent() != 1 for single value type: output.subscribed-indices.values
    extent() != 1 for single value type: input.buffers.allocator-ids.values
D/ReflectedParamUpdater: extent() != 1 for single value type: output.buffers.allocator-ids.values
D/ReflectedParamUpdater: extent() != 1 for single value type: algo.buffers.allocator-ids.values
    extent() != 1 for single value type: output.buffers.pool-ids.values
D/ReflectedParamUpdater: extent() != 1 for single value type: algo.buffers.pool-ids.values
I/CCodecConfig: query failed after returning 7 values (BAD_INDEX)
D/CCodecConfig: c2 config diff is Dict {
      c2::u32 coded.bitrate.value = 64000
      c2::u32 input.buffers.max-size.value = 8192
      c2::u32 input.delay.value = 0
      string input.media-type.value = "audio/mpeg"
      string output.media-type.value = "audio/raw"
      c2::u32 raw.channel-count.value = 2
      c2::u32 raw.sample-rate.value = 44100
    }
D/CCodec: [c2.android.mp3.decoder] buffers are bound to CCodec for this session
D/CCodecConfig: no c2 equivalents for durationUs
    no c2 equivalents for track-id
    no c2 equivalents for encoder-delay
    no c2 equivalents for encoder-padding
    no c2 equivalents for flags
D/CCodecConfig: c2 config diff is   c2::u32 raw.channel-count.value = 1
      c2::u32 raw.sample-rate.value = 48000
W/Codec2Client: query -- param skipped: index = 1107298332.
D/CCodec: setup formats input: AMessage(what = 0x00000000) = {
      int32_t channel-count = 1
      int32_t max-input-size = 8192
      string mime = "audio/mpeg"
      int32_t sample-rate = 48000
    } and output: AMessage(what = 0x00000000) = {
      int32_t channel-count = 1
      string mime = "audio/raw"
      int32_t sample-rate = 48000
      int32_t encoder-delay = 528
      int32_t encoder-padding = 2393
    }
W/Codec2Client: query -- param skipped: index = 1342179345.
    query -- param skipped: index = 2415921170.
E/FMQ: grantorIdx must be less than 3
    grantorIdx must be less than 3
D/CCodecBufferChannel: [c2.android.mp3.decoder#144] Created input block pool with allocatorID 16 => poolID 19 - OK (0)
I/CCodecBufferChannel: [c2.android.mp3.decoder#144] Created output block pool with allocatorID 16 => poolID 28 - OK
D/CCodecBufferChannel: [c2.android.mp3.decoder#144] Configured output block pool ids 28 => OK
E/FMQ: grantorIdx must be less than 3
E/FMQ: grantorIdx must be less than 3
D/CCodecBufferChannel: [c2.android.mp3.decoder#144] MediaCodec discarded an unknown buffer
I/chatty: uid=10153(com.example.noteswiktorapp) identical 1 line
D/CCodecBufferChannel: [c2.android.mp3.decoder#144] MediaCodec discarded an unknown buffer
I/hw-BpHwBinder: onLastStrongRef automatically unlinking death recipients
D/AudioTrack: createTrack_l(0): AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount 0 -> 109368
D/BufferPoolAccessor2.0: bufferpool2 0xf1a47838 : 0(0 size) total buffers - 0(0 size) used buffers - 0/5 (recycle/alloc) - 4/194 (fetch/transfer)
    evictor expired: 1, evicted: 1
I/.noteswiktorap: Thread[3,tid=7102,WaitingInMainSignalCatcherLoop,Thread*=0xe3fcc410,peer=0x13040268,"Signal Catcher"]: reacting to signal 3
D/BufferPoolAccessor2.0: bufferpool2 0xf1a48c68 : 0(0 size) total buffers - 0(0 size) used buffers - 0/5 (recycle/alloc) - 4/210 (fetch/transfer)
    evictor expired: 1, evicted: 1
I/.noteswiktorap: Wrote stack traces to tombstoned
D/BufferPoolAccessor2.0: bufferpool2 0xf1a4e8d8 : 0(0 size) total buffers - 0(0 size) used buffers - 0/5 (recycle/alloc) - 4/184 (fetch/transfer)
    evictor expired: 1, evicted: 1
D/AudioTrack: createTrack_l(5): AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount 0 -> 103063
java
android
android-activity
asked on Stack Overflow Nov 12, 2020 by LoveAndMercy • edited Nov 14, 2020 by David Wasser

1 Answer

0

You are running

for (int i = 0; i < 10; i++) {
    try {
        TimeUnit.SECONDS.sleep(timeCycle);
        randomNote();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

on the UI thread. This is causing the UI changes to freeze until the loop is completed. If you want to have an active UI while running this code, you use Handler:

new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    TimeUnit.SECONDS.sleep(timeCycle); 
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            randomNote();
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

        }
    }, 0);
answered on Stack Overflow Nov 12, 2020 by Dan Baruch • edited Nov 12, 2020 by Dan Baruch

User contributions licensed under CC BY-SA 3.0