user9186194
user9186194

Reputation:

How to implement Runnable for the given code?

I'm trying to play sounds on tap of a button. Initially the sound is played on tap, but after repeated tap of a button the sound isn't played anymore. All the required files are placed in respective folders.

<GridLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <Button
        android:id="@+id/one"
        android:layout_width="wrap_content"
        android:layout_height="80dp"
        android:layout_column="0"
        android:layout_columnWeight="1"
        android:layout_row="0"
        android:layout_rowWeight="1"
        android:background="@drawable/one"
        android:onClick="tapped"
        android:tag="0"
        android:text="@string/one"
        tools:text="@string/one" />

    <Button
        android:id="@+id/two"
        android:layout_width="wrap_content"
        android:layout_height="80dp"
        android:layout_column="1"
        android:layout_columnWeight="1"
        android:layout_row="0"
        android:layout_rowWeight="1"
        android:background="@drawable/two"
        android:onClick="tapped"
        android:tag="1"
        android:text="@string/two"
        tools:text="@string/two" />

        </GridLayout>

Here's what I have done as of now,

public class MainActivity extends AppCompatActivity {

 int myMusic[] = {R.raw.one,R.raw.two};

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


 public void tapped ( final View view){
        Button buttonVar = (Button) view;
        int tagNo;
        tagNo = Integer.parseInt(buttonVar.getTag().toString());
        MediaPlayer sound = MediaPlayer.create(this, myMusic[tagNo]);
        sound.start();

Upvotes: 0

Views: 82

Answers (2)

Fabricio20
Fabricio20

Reputation: 508

Aside from sourabh's answer (to release the used MediaPlayer), to properly implement multi-threading (as the question asks) you will need to submit a runnable into a ThreadPool.

Google/Android provides documentation on ExecutorService(s), linked below, which you can follow to get an understanding on how to run chunks of code on new threads.

Beware though, as when running things async you can still have duplicate playback (unless not handled) as multiple audio sources will be started (one for each submitted thread).

https://developer.android.com/reference/java/util/concurrent/ExecutorService.html

Upvotes: 0

sourabhgupta811
sourabhgupta811

Reputation: 106

release your mediaplayer after you are done with it. you are creating multiple mediaplayer instances and that is causing the problem.

use-

    sound.release();

Upvotes: 2

Related Questions