I have edited and tried many methods. Basically there is button. What i want that if i click it, it will start playing sound 'norse' again after every 5 seconds, till i click that button again. I wrote script what seems fine for me but it every time crashes :(. Here is code and errors, can you help?
//BUTTON SHIT\\
teebheli = false;
magamine = MediaPlayer.create(this, R.raw.norse);
bhelitegija = (Button) findViewById(R.id.bTeeHeli);
bhelitegija.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (teebheli == false ){
bhelitegija.setText("Lõpeta heli!");
magamine.start();
teebheli = true;
}
if (teebheli == true) {
bhelitegija.setText("Tee heli!");
magamine.stop();
teebheli = false;
}
}
});
piiksumine = new Thread(){
public void run(){
try {
int piiksumine = 0;
while (piiksumine < 5000) {
开发者_运维知识库 sleep(100);
piiksumine = piiksumine + 100;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
piiksumine.start();
}
}
};
AND error when I click on button:
08-11 18:09:36.738: ERROR/MediaPlayer(1224): start called in state 0
08-11 18:09:36.738: ERROR/MediaPlayer(1224): error (-38, 0)
08-11 18:09:36.746: ERROR/MediaPlayer(1224): stop called in state 0
08-11 18:09:36.746: ERROR/MediaPlayer(1224): error (-38, 0)
08-11 18:09:36.777: ERROR/MediaPlayer(1224): Error (-38,0)
08-11 18:09:36.786: ERROR/MediaPlayer(1224): Error (-38,0)
You have not set a name for the PreferenceManager.getDefaultSharedPreferencesName
.
(Off the top of my head, but try something like the following):
PreferenceManager.setDefaultValues(context, sharedPreferencesName,
sharedPreferencesMode, resId, readAgain);
Do this before you try to get shared preferences.
Put whatever you like in for the values, check the documentation if the variable names aren't clear :)
Hope this helps!
EDIT:
Now you are trying to access a MediaPlayer instantiated in another thread. You can't do this. You need to MediaPlayer.create() and MediaPlayer.start() in the same thread.
Well one implementation would be to just start an async task, and start an infinite loop, in the loop keep asking for the system time, compare the time with the initial time, if time passed is equal to five second just fire the beep.
There is a lot of piiksumine in your Thread, whatever that means, I'd rather give the Thread and the int different names.
Also I'm not sure I understand well what is intended here, but I don't think you should start the thread in its own run() method with piiksumine.start();
You could try using android.os.CountDownTimer instead and use long countdown. There is a method onTick() that you could leverage to play the sound (by setting to 5 seconds for countDownInterval in constructor). You could stop it by calling cancel() the next time the button is pressed.
精彩评论