当我的应用程序中播放音乐时,我试图让背景闪烁,但它没有按预期工作。
按下按钮时播放音乐。音乐关闭时背景应为黄色,但在播放音乐时背景应在黄色和紫色之间快速闪烁。
此刻关闭时为黄色,播放音乐时变为暗灰色,关闭音乐时不返回黄色。
public class InstaRave extends Activity {
private static final String TAG = "InstaRave";
private static int isPlaying = 0; // 0 is not playing 1 is playing
private MediaPlayer mp;
public static int mPurple = color.mPurple;
public static int mYellow = color.mYellow;
public static int currentBackground = mYellow;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insta_rave);
final Button play_button = (Button)this.findViewById(R.id.raveButton);
final RelativeLayout mRelativeLayout = (RelativeLayout) this.findViewById(R.id.topLevelLayout);
mp = MediaPlayer.create(this, R.raw.rave_mk);
Log.v(TAG, "Initializing sounds...");
play_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch (isPlaying){
case 0:
changeBackground(mRelativeLayout);
startMusic();
isPlaying = 1;
rave();
break;
case 1:
changeBackground(mRelativeLayout);
stopMusic();
isPlaying = 0;
rave();
break;
default:
Log.e(TAG, "Ooops something went wrong");
}
}
private void stopMusic(){
Log.v(TAG, "Stopping sound...");
mp.stop();
//isPlaying = 0;
mp.prepareAsync();
}
private void startMusic(){
Log.v(TAG, "Playing sound...");
mp.start();
//isPlaying = 1;
}
private void rave(){
Log.v(TAG, String.valueOf(isPlaying));
if (isPlaying == 1){
Log.v(TAG, "Raving....");
new Rave().execute();
} else {
Log.v(TAG, "End the rave the po po is here...");
}
}
});
}
protected void onPause(){
super.onPause();
mp.release();
mp = null;
}
private void changeBackground(RelativeLayout mRelativeLayout){
if (currentBackground == mYellow){
currentBackground = mPurple;
mRelativeLayout.setBackgroundColor(currentBackground);
Log.v(TAG, "Background is: " + String.valueOf(currentBackground));
}
currentBackground = mYellow;
mRelativeLayout.setBackgroundColor(currentBackground);
Log.v(TAG, "Background is: " + String.valueOf(currentBackground));
}
private class Rave extends AsyncTask<Void, Void, Void> {
final RelativeLayout mRelativeLayout = (RelativeLayout) findViewById(R.id.topLevelLayout);
@Override
protected Void doInBackground(Void... params) {
while (isPlaying ==1){
try {
Thread.sleep(75);
publishProgress();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
protected void onProgressUpdate(Void... progress){
changeBackground(mRelativeLayout);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.insta_rave, menu);
return true;
}
}