Reputation: 1
I would like to use the same button to start and stop playing some sounds with a for loop inside function play(). I thought to use lock variable to do this, but button after click remains pressed till the function play end is execution. Can you suggest some solution?
I have a situation like this:
public class MainActivity extends Activity {
private static SoundPool sound;
static int lock=1;
int s;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sound=new SoundPool(20, AudioManager.STREAM_MUSIC, 100);
s=sound.load(this,R.raw.bipsound, 0);
Button button = (Button) findViewById(R.id.button);
}
public void onClick(View v) {
switch(lock) {
case 0:
lock=1;
break;
case 1:
lock=0;
play();
break;
}
}
public void play(){
for(int i=0;i<10;i++){
sound.play(s,1.0f, 1.0f, 1, 0, 1);
if(lock==1)
return;
try {Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Upvotes: 0
Views: 146
Reputation: 2671
That's normal because you're using try {Thread.sleep(1000);
and it stop the main thread during 1 seconde.
You've to use an AsyncTask to do that :)
Here's an example.
private void goToMainActivity() {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Intent intent = new Intent(fa, Main.class);
startActivity(intent);
}
}.execute();
}
Upvotes: 0
Reputation: 44571
This is a problem try {Thread.sleep(1000);
inside play()
. You are telling the main Thread
to sleep
which is almost always a bad idea. The Button
becomes pressed and remains in that state until the sleep()
time has finished.
Remove that line. And I'm not sure what you are trying to accomplish there but you can run it in a separate Thread
with things like TimerTask
, use a handler
or other such features. If you need more help then please explain what you are trying to do with that.
Upvotes: 1