Will the activity of Android – ontouchevent() be triggered 3 times?
In my titlescreen activity, I have
@Override
public boolean onTouchEvent(MotionEvent event)
{
Log.d("MyActivity", "in onTouchEvent!");
MediaPlayer myplayer = MediaPlayer.create(TitleScreen.this, R.raw.mysound);
myplayer.start();
startActivity(new Intent("com.example.GAME"));
return super.onTouchEvent(event);
}
This causes the sound to play quickly and continuously three times when clicking on the screen, making the sound I want to play have a delayed echo. I checked the log and my "ontouchevent!" message was recorded three times
This activity is just a static image of the title screen. You can click it to start the next activity. When you do so, the specified sound should be the player
For my specific problem, I can solve it by placing a global level int variable:
private static int playerInstances = 0;
Then wrap it with my mediaplayer line:
if (playerInstances == 0)
{
MediaPlayer myplayer = MediaPlayer.create(TitleScreen.this, R.raw.critical1);
myplayer.start();
playerInstances++;
}
This ensures that the code is executed only once. So my problem is solved. I just want to know why I click ontouchevent three times at a time
resolvent:
What you actually do on ontouchevent (better than using static variables) is:
@Override
public boolean onTouchEvent(MotionEvent event) {
final int action = event.getAction();
if(action == MotionEvent.ACTION_DOWN) {
Log.d("MyActivity", "in onTouchEvent!");
MediaPlayer myPlayer = MediaPlayer.create(TitleScreen.this, R.raw.mysound);
myPlayer.start();
startActivity(new Intent("com.example.GAME"));
}
return super.onTouchEvent(event);
}