In music play class, declare more variables.
int dem = 0;
int dem2=0;
private final Handler handler = new Handler();
Copy this function in to above last
close bracket.
Runnable
notification;
private void play() {
if (mPlayer.isPlaying()) {
notification = new Runnable() {
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
public void run() {
play();
}
};
handler.postDelayed(notification, 1000);
}
else{
if (dem2 == 1) {
mPlayer.pause();
} else {
dem = dem + 1;
if (dem == mMusicList.size()) {
dem = 0;
}
mPlayer.reset();
String path=mAudioPath.get(dem);
try
{
mPlayer.setDataSource(path);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mPlayer.start();
play();
}
}
}
We use handler to check, if no music that mean song stop, we play
next song.
Replace all command in listView by these lines.
dem2=0;
dem=arg2-1;
if (mPlayer.isPlaying()) {
mPlayer.reset();
handler.removeCallbacks(notification);
}
play();
To playing when screen lock, add this.
@Override
public void onPause() {
super.onPause();
play();
}
Last, we have to exit handler when quit class.
@Override
public void onStop() {
super.onStop();
handler.removeCallbacks(notification);
}
You can put this command in Quit button or Back button, or in onDestroy()command.
Choose what run effective.
If you want next song can be any song. Random a variable from 0 to smaller
than array size one digit, change function play to add song id to.
If you want to set song name to a textView float on bottom of
listview. Create a textView in RelativeLayout and set position like this.
android:layout_alignParentBottom="true". And for
ListView use android:layout_above="@+id/textview".
After that add to function play() and in to command of listView.
songname.setText(mMusicList.get(dem));
Some time we need to check handler running or not, to avoid
duplicate.
Create a variable name boolean isRunning = false;
Add to run command in function play.
private void play() {
if (mPlayer.isPlaying()) {
notification = new Runnable() {
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
public void run() {
isRunning = true;
play();
}
};
handler.postDelayed(notification,
1000);
}
If value is true, handler is running.
No comments:
Post a Comment