I am fairly new to android development, so what I am trying to make is an app that can play audio from url,
I want to show progress bar while the audio file is loading from the web(some audio files are big over 15mb) How can I do that?
here is my audio play activity
public class AudioPlayerActivity extends AppCompatActivity {
String Content_id,audio_url;
AudioView audioView;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_player);
audio_url = getIntent().getStringExtra("audio_url");
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
audioView=(AudioView)findViewById(R.id.audioview);
//pDialog.setMessage("Please Wait...");
//showDialog();
try {
audioView.setDataSource(audio_url);
audioView.start();
} catch (IOException e) {
e.printStackTrace();
}
//hideDialog();
}
#SuppressLint("MissingSuperCall")
#Override
protected void onStop() {
super.onPause();
audioView.pause();
}
#Override
protected void onDestroy() {
super.onDestroy();
audioView.pause();
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
I am sharing the whole code for a well customized MediaPlayer. Just follow and implement this -
public class MusicActivity extends AppCompatActivity implements MediaPlayer.OnCompletionListener, SeekBar.OnSeekBarChangeListener {
private ImageView cross, settings;
private TextView titleText;
private RecyclerView recyclerView;
private ProgressBar mProgressBar;
private String id;
private String title;
private String audio;
private String english;
private String transliteration;
private String urdu;
private LinearLayoutManager linearLayoutManager;
private ProgressDialog progressDialog;
private float scrollTo;
private ImageView play_button;
private View view;
private TextView audiotitle;
private LinearLayout hide;
private ImageView play, rewind, forward;
private TextView currentTime, endTime;
private SeekBar seekbar;
private RelativeLayout progress_layout;
private LinearLayout offline_layout;
private ImageView download;
private ImageView cancel;
private Dialog mBottomSheetDialog;
private MediaPlayer mp;
private Handler mHandler = new Handler();
private Util util;
private boolean flag = false;
private ProgressBar progressBar;
Boolean isInternetPresent = false;
ConnectionDetector cd;
private String open_download_string;
private ProgressBar mProgress;
private ArrayList<String> filePath = new ArrayList<String>();
private int seekForwardTime = 10 * 1000;
private int seekBackwardTime = 10 * 1000;
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
if (mp != null) {
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
// Displaying Total Duration time
endTime.setText(util.milliSecondsToTimer(totalDuration) + " min");
// Displaying time completed playing
currentTime.setText(util.milliSecondsToTimer(currentDuration) + " min");
// Updating progress bar
int progress = (int) (util.getProgressPercentage(currentDuration, totalDuration));
seekbar.setProgress(progress);
mHandler.postDelayed(this, 100);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_player);
mp = new MediaPlayer();
cross = (ImageView) findViewById(R.id.cross);
settings = (ImageView) findViewById(R.id.settings);
titleText = (TextView) findViewById(R.id.title);
play_button = (ImageView) findViewById(R.id.play_button);
setMusicPlayerWidgets();
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
title = bundle.getString(Constant.SONG_TITLE);
audio = bundle.getString(Constant.SONG_AUDIO);
/*mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp) {
play_button.setVisibility(View.VISIBLE);
if(mp.isPlaying()){
if(mp!=null){
play_button.setImageResource(R.drawable.pause);
}
}else{
play_button.setImageResource(R.drawable.play);
}
}
});*/
/* play_button.setVisibility(View.VISIBLE);
if(mp.isPlaying()){
if(mp!=null){
play_button.setImageResource(R.drawable.pause);
}
}else{
play_button.setImageResource(R.drawable.play);
}*/
} else {
progressBar.setVisibility(View.GONE);
play_button.setVisibility(View.GONE);
}
titleText.setText(title);
}
}
#Override
public void onResume() {
super.onResume();
setUpMusicPlayer();
}
/**
* MUSIC PLAYER IMPLEMENTATION
**/
private void setMusicPlayerWidgets() {
view = getLayoutInflater().inflate(R.layout.media_player_layout, null);
play = (ImageView) view.findViewById(R.id.play);
rewind = (ImageView) view.findViewById(R.id.rewind);
forward = (ImageView) view.findViewById(R.id.forward);
audiotitle = (TextView) view.findViewById(R.id.title);
hide = (LinearLayout) view.findViewById(R.id.hide);
seekbar = (SeekBar) view.findViewById(R.id.seekbar);
currentTime = (TextView) view.findViewById(R.id.time_current);
endTime = (TextView) view.findViewById(R.id.time_end);
progress_layout = (RelativeLayout) view.findViewById(R.id.progress_layout);
offline_layout = (LinearLayout) view.findViewById(R.id.offline_layout);
download = (ImageView) view.findViewById(R.id.download);
cancel = (ImageView) view.findViewById(R.id.cancel);
mBottomSheetDialog = new Dialog(DuaReadingsActivity.this, R.style.MaterialDialogSheet);
}
private void setUpMusicPlayer() {
audiotitle.setText(title);
seekbar.setOnSeekBarChangeListener(this);
mp.setOnCompletionListener(this);
play_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp.isPlaying()) {
if (mp != null) {
play_button.setImageResource(R.drawable.play);
play.setImageResource(R.drawable.play_button);
mp.pause();
}
} else {
play_button.setImageResource(R.drawable.pause);
play.setImageResource(R.drawable.pause_button);
if (flag == false) {
playSong();
flag = true;
} else {
mp.start();
}
File dirFiles = DuaReadingsActivity.this.getFilesDir();
for (String strFile : dirFiles.list()) {
filePath.add(strFile);
}
if (!filePath.contains(open_download_string)) {
cd = new ConnectionDetector(DuaReadingsActivity.this);
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
new DownloadFileFromURL().execute(audio);
} else {
cd.noInternetDialog();
}
}
mediaBottomSheet();
}
}
});
}
private void mediaBottomSheet() {
mBottomSheetDialog.setContentView(view);
mBottomSheetDialog.setCancelable(true);
mBottomSheetDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mBottomSheetDialog.getWindow().setGravity(Gravity.BOTTOM);
mBottomSheetDialog.show();
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
if (mBottomSheetDialog.isShowing()) {
mBottomSheetDialog.dismiss();
}
}
};
mBottomSheetDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// handler.removeCallbacks(runnable);
}
});
handler.postDelayed(runnable, 10000);
hide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mBottomSheetDialog.dismiss();
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp.isPlaying()) {
if (mp != null) {
play_button.setImageResource(R.drawable.play);
play.setImageResource(R.drawable.play_button);
mp.pause();
}
} else {
play_button.setImageResource(R.drawable.pause);
play.setImageResource(R.drawable.pause_button);
if (flag == false) {
playSong();
flag = true;
} else {
mp.start();
}
}
}
});
rewind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rewindSong();
}
});
forward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
forwardSong();
}
});
}
public void rewindSong() {
if (mp != null) {
int currentPosition = mp.getCurrentPosition();
if (currentPosition - seekBackwardTime >= 0) {
mp.seekTo(currentPosition - seekBackwardTime);
} else {
mp.seekTo(0);
}
}
}
public void forwardSong() {
if (mp != null) {
int currentPosition = mp.getCurrentPosition();
if (currentPosition + seekForwardTime <= mp.getDuration()) {
mp.seekTo(currentPosition + seekForwardTime);
} else {
mp.seekTo(mp.getDuration());
}
}
}
#Override
public void onCompletion(MediaPlayer arg0) {
if (mBottomSheetDialog.isShowing()) {
mBottomSheetDialog.dismiss();
}
play_button.setImageResource(R.drawable.play);
play.setImageResource(R.drawable.play_button);
mp.seekTo(0);
flag = false;
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp.isPlaying()) {
if (mp != null) {
play_button.setImageResource(R.drawable.play);
play.setImageResource(R.drawable.play_button);
mp.pause();
}
} else {
play_button.setImageResource(R.drawable.pause);
play.setImageResource(R.drawable.pause_button);
if (flag == false) {
playSong();
flag = true;
} else {
mp.start();
}
}
}
});
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTimeTask);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mp.getDuration();
int currentPosition = util.progressToTimer(seekBar.getProgress(), totalDuration);
// forward or backward to certain seconds
mp.seekTo(currentPosition);
// update timer progress again
updateProgressBar();
}
public void playSong() {
try {
/*mp.reset();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(audio);
mp.prepare();*/
mp.start();
play_button.setImageResource(R.drawable.pause);
play.setImageResource(R.drawable.pause_button);
seekbar.setProgress(0);
seekbar.setMax(100);
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} /*catch (IOException e) {
e.printStackTrace();
}*/
}
public void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100);
}
#Override
public void onDestroy() {
super.onDestroy();
try {
mp.reset();
mp.prepareAsync();
mp.stop();
mp.release();
mp = null;
} catch (Exception e) {
e.printStackTrace();
}
final Handler handler = new Handler();
new Runnable() {
public void run() {
finish();
handler.postDelayed(this, 150);
}
};
}
#Override
public void onBackPressed() {
super.onBackPressed();
try {
mp.reset();
mp.prepareAsync();
mp.stop();
mp.release();
mp = null;
} catch (Exception e) {
e.printStackTrace();
}
final Handler handler = new Handler();
new Runnable() {
public void run() {
finish();
handler.postDelayed(this, 150);
}
};
if((mProgress != null) && (mProgress.getProgress() != 0)){
File file = new File(DuaReadingsActivity.this.getFilesDir() + "/" +open_download_string);
file.delete();
if(file.exists()){
try {
file.getCanonicalFile().delete();
} catch (IOException e) {
e.printStackTrace();
}
if(file.exists()){
getApplicationContext().deleteFile(file.getName());
}
}
}
// finish();
}
#Override
protected void onPause() {
super.onPause();
if (mp.isPlaying()) {
mp.pause();
}
}
#Override
protected void onStop() {
super.onStop();
if (mp.isPlaying()) {
mp.pause();
}
}
private class DownloadFileFromURL extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progress_layout.setVisibility(View.VISIBLE);
download.setVisibility(View.GONE);
offline_layout.setVisibility(View.GONE);
mProgress = (ProgressBar) view.findViewById(R.id.circularProgressbar);
mProgress.setProgress(0);
mProgress.setSecondaryProgress(100);
mProgress.setMax(100);
mProgress.setIndeterminate(false);
mProgress.setProgressDrawable(getResources().getDrawable(R.drawable.download_progress));
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(), 8192);
FileOutputStream outputStream = openFileOutput(audio.substring(audio.lastIndexOf('/') + 1), Context.MODE_PRIVATE);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) ((total * 100) / lenghtOfFile));
outputStream.write(data, 0, count);
}
outputStream.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String file_url) {
getFilesDir().getAbsolutePath();
progress_layout.setVisibility(View.GONE);
download.setVisibility(View.GONE);
offline_layout.setVisibility(View.VISIBLE);
mProgress.setProgress(0);
}
#Override
protected void onProgressUpdate(Integer... progress) {
mProgress.setProgress(progress[0]);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
progress_layout.setVisibility(View.GONE);
download.setVisibility(View.VISIBLE);
offline_layout.setVisibility(View.GONE);
mProgress.setProgress(0);
DownloadFileFromURL.this.cancel(true);
File file = new File(DuaReadingsActivity.this.getFilesDir() + "/" +open_download_string);
file.delete();
if(file.exists()){
try {
file.getCanonicalFile().delete();
} catch (IOException e) {
e.printStackTrace();
}
if(file.exists()){
getApplicationContext().deleteFile(file.getName());
}
}
}
});
download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
progress_layout.setVisibility(View.VISIBLE);
download.setVisibility(View.GONE);
offline_layout.setVisibility(View.GONE);
cd = new ConnectionDetector(DuaReadingsActivity.this);
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
new DownloadFileFromURL().execute(audio);
} else {
cd.noInternetDialog();
}
}
});
}
}
}
This will work perfectly if you follow well. Cheers!!
Ok so I have an activity where I display a song that's playing, and I created another layout for landscape mode, I have an imageview that displays the album art from that song and a title in the actionbar, all display information of the playing song, but when I rotate the screen and then rotate back to portrait mode and switch song with my next button and then rotate on that other song, it still displays information of the previous song.
My first activity (displays all songs)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_songs);
recyclerView = findViewById(R.id.recyclerView);
if (recyclerView != null) {
recyclerView.setHasFixedSize(true);
}
songAdapter = new SongAdapter(this, songList);
recyclerView.setAdapter(songAdapter);
songAdapter.notifyDataSetChanged();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), linearLayoutManager.getOrientation());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.addItemDecoration(dividerItemDecoration);
//RelativeLayouts
mainLayout = findViewById(R.id.mainLayout);
secondLayout = findViewById(R.id.secondLayout);
currSong = findViewById(R.id.currSong);
//LinearLayouts
songThumbnail = findViewById(R.id.songThumbnail);
mToolbar = findViewById(R.id.mToolbar);
setSupportActionBar(mToolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(R.string.library);
}
tvCurrSongTitle = findViewById(R.id.tvCurrSongTitle);
tvCurrSongArtist = findViewById(R.id.tvCurrSongArtist);
recyclerView.addOnItemTouchListener(new OnItemClickListeners(this, new OnItemClickListeners.OnItemClickListener() {
#TargetApi(Build.VERSION_CODES.O)
#Override
public void onItemClick(View view, int position) {
songIndex = position;
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(songList.get(songIndex).getData());
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
Toast.makeText(getApplicationContext(), "You Clicked position: " + position + " " + songList.get(position).getData(), Toast.LENGTH_SHORT).show();
tvCurrSongTitle.setText(songList.get(position).getTitle());
tvCurrSongArtist.setText(songList.get(position).getArtist());
} catch (Exception e) {
e.printStackTrace();
}
}
}));
currSong.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent currSong = new Intent(getApplicationContext(), SongActivity.class);
currSong.putExtra("songIndex", songIndex);
startActivity(currSong);
}
});
My Song activity class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_song);
albumArtLarge = findViewById(R.id.albumArtLarge);
albumArt = findViewById(R.id.albumArt);
mBtnPlayPause = findViewById(R.id.mBtnPlayPause);
mBtnNext = findViewById(R.id.mBtnNext);
mBtnPrev = findViewById(R.id.mBtnPrev);
mBtnShuffle = findViewById(R.id.mBtnShuffle);
mBtnRepeat = findViewById(R.id.mBtnRepeat);
seekBar = findViewById(R.id.seekBar);
tvSongCurrentTime = findViewById(R.id.tvSongCurrentTime);
tvSongTotalTime = findViewById(R.id.tvSongTotalTime);
tvSongListSize = findViewById(R.id.tvSongListSize);
//Listeners
seekBar.setOnSeekBarChangeListener(this);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
Intent currSong = getIntent();
b = currSong.getExtras();
mCurrentIndex = (int) b.get("songIndex");
songActivityToolbar = findViewById(R.id.songActivityToolbar);
setSupportActionBar(songActivityToolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(songList.get(songIndex).getTitle());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
// Load album art clicked song
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, songList.get(songIndex).getAlbumid());
Picasso.with(this)
.load(albumArtUri)
.error(R.drawable.blackgreygradientbackground)
.into(albumArtLarge);
Picasso.with(this)
.load(albumArtUri)
.error(R.drawable.albumcover)
.resize(500,500)
.into(albumArt);
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mBtnPlayPause.setImageResource(R.drawable.ic_action_pause_white);
tvSongListSize.setText((mCurrentIndex + 1) + "/" + songList.size());
updateProgressBar();
}
}
mBtnShuffle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isShuffle){
isShuffle = false;
Toast.makeText(getApplicationContext(), "Shuffle is off", Toast.LENGTH_SHORT ).show();
mBtnShuffle.setImageResource(R.drawable.ic_action_shuffle);
}else{
isShuffle = true;
Toast.makeText(getApplicationContext(), "Shuffle is on", Toast.LENGTH_SHORT).show();
mBtnShuffle.setImageResource(R.drawable.ic_shuffle_on);
isRepeat = false;
mBtnRepeat.setImageResource(R.drawable.ic_action_repeat);
}
}
});
mBtnRepeat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isRepeat){
isRepeat = false;
Toast.makeText(getApplicationContext(), "Repeat is off", Toast.LENGTH_SHORT).show();
mBtnRepeat.setImageResource(R.drawable.ic_action_repeat);
}else{
isRepeat = true;
Toast.makeText(getApplicationContext(), "Repeat is on", Toast.LENGTH_SHORT).show();
mBtnRepeat.setImageResource(R.drawable.ic_repeat_on);
isShuffle = false;
mBtnShuffle.setImageResource(R.drawable.ic_action_shuffle);
}
}
});
mBtnPlayPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
mBtnPlayPause.setImageResource(R.drawable.ic_action_play);
} else {
mediaPlayer.start();
mBtnPlayPause.setImageResource(R.drawable.ic_action_pause_white);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
mBtnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nextSong();
}
});
mBtnPrev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
prevSong();
}
});
}
private void playSongNumber(final int index) {
try{
mediaPlayer.reset();
mediaPlayer.setDataSource(songList.get(index).getData());
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(songList.get(index).getTitle());
}
//Load album art
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, songList.get(index).getAlbumid());
Picasso.with(getApplicationContext())
.load(albumArtUri)
.error(R.drawable.blackgreygradientbackground)
.into(albumArtLarge);
Picasso.with(getApplicationContext())
.load(albumArtUri)
.error(R.drawable.albumcover)
.resize(500,500)
.into(albumArt);
updateProgressBar();
}
});
seekBar.setProgress(0);
seekBar.setMax(100);
}catch (Exception e){
e.printStackTrace();
}
}
private void nextSong(){
mCurrentIndex++;
mCurrentIndex %= songList.size();
playSongNumber(mCurrentIndex);
mBtnPlayPause.setImageResource(R.drawable.ic_action_pause_white);
tvSongListSize.setText((mCurrentIndex + 1) + "/" + songList.size());
Toast.makeText(getApplicationContext(), "You Clicked position: " + mCurrentIndex + " " + songList.get(mCurrentIndex).getData(), Toast.LENGTH_SHORT).show();
}
private void prevSong(){
mCurrentIndex = mCurrentIndex > 0 ? mCurrentIndex - 1 : songList.size() - 1;
playSongNumber(mCurrentIndex);
mBtnPlayPause.setImageResource(R.drawable.ic_action_pause_white);
tvSongListSize.setText((mCurrentIndex + 1) + "/" + songList.size());
Toast.makeText(getApplicationContext(), "You Clicked position: " + mCurrentIndex + " " + songList.get(mCurrentIndex).getData(), Toast.LENGTH_SHORT).show();
}
#Override
public void onCompletion(MediaPlayer mp) {
if (isRepeat){
playSongNumber(mCurrentIndex);
}else if(isShuffle){
Random random = new Random();
mCurrentIndex = random.nextInt((songList.size() - 1) + 1);
tvSongListSize.setText((mCurrentIndex + 1) + "/" + songList.size());
playSongNumber(mCurrentIndex);
}else if (mCurrentIndex < songList.size()-1){
mediaPlayer.reset();
nextSong();
tvSongListSize.setText((mCurrentIndex + 1) + "/" + songList.size());
}else{
playSongNumber(0);
tvSongListSize.setText((1) + "/" + songList.size());
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(getApplicationContext(), "what:" + what + "extra:" +extra , Toast.LENGTH_SHORT).show();
return true;
}
private Runnable mUpdateTime = new Runnable() {
#Override
public void run() {
long songCurrentTime = mediaPlayer.getCurrentPosition();
long songTotalTime = mediaPlayer.getDuration();
tvSongCurrentTime.setText(""+utilities.msToTimer(songCurrentTime));
tvSongTotalTime.setText(""+utilities.msToTimer(songTotalTime));
int progress = (int)(utilities.getProgressPercentage(songCurrentTime, songTotalTime));
seekBar.setProgress(progress);
mHandler.postDelayed(this, 100);
}
};
public void updateProgressBar(){
mHandler.postDelayed(mUpdateTime, 100);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTime);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTime);
int songTotalTime = mediaPlayer.getDuration() ;
int currentPosition = utilities.progressToTimer(seekBar.getProgress(), songTotalTime);
mediaPlayer.seekTo(currentPosition);
updateProgressBar();
}
}
How can I update the album art on rotation, it only occurs when I rotate the screen, in portrait mode it all works fine and updates the information when I change the song.
Hi am trying to stream online radio while opening my app when buffering first time it runs fine while i close the app and then start again the app it plays from where the player last closed and then stopped after it ends and i have to startup manually to stream the url for current level of radio
my coding:
public class MainActivity extends AppCompatActivity {
DrawerLayout drawer;
ImageView list_activity_check;
ImageView share,speaker,mute, control;
DrawerListAdapter drawerListAdapter;
ListView listview_nav;
private SmallBang mSmallBang;
String [] Items={"Program Lists","Rate app"} ;
int [] images={R.drawable.pro_logo,
R.drawable.rate_icon} ;
String[] titles = {
"Ippadikku Idhayam",
"Akilam 360",
"Cine Pattarai",
"Palsuvai Thoranam",
"Pesum Noolagam",
"Lollu Cafe",
"Kavi Saagaram",
"Aa muthal Akk",
"Thiraicholai",
"Kathamba Saaral",
"Paarkatha Pakkangal",
"Pagadi Panna Porom",
};
public static final String[] fromtime = new String[]{"10:30 AM","12:30 PM","14:30 PM","16:30 PM","18:30 PM","20:30 PM","22:30 PM","00:30 AM","02:30 AM","04:30 AM","06:30 AM","08:30 AM"};
public static final String[] totime = new String[]{"12:30 PM","14:30 PM","16:30 PM","18:30 PM","20:30 PM","22:30 PM","00:30 AM","02:30 AM","04:30 AM","06:30 AM","08:30 AM","10:30 AM"};
Integer[] images0 = {
R.drawable.ipadikku_idhayam,
R.drawable.akilam_360,
R.drawable.cine_pattarai,
R.drawable.palsuvai_thoranam,
R.drawable.pesum_noolagam,
R.drawable.lollu_cafe,
R.drawable.kavi_saagaram,
R.drawable.aa_muthal_akk,
R.drawable.thiraicholai,
R.drawable.kathamba_saaral,
R.drawable.paarkatha_pakkangal,
R.drawable.pagadi_panna_porom,
};
//************* Current Show ***************//
ListView list,lvshow;
List<Program> rowItems;
int iImageId;
String sTitle,sFrom,sTo ;
SQLiteDatabase db;
ImageView music;
int media1;
int intValue1;
AdapAdapter Adapadapter;
ArrayList<String> iTitle = null;
ArrayList<String> sQuantity = null;
ArrayList<String> sQuantity1 = null;
ArrayList<String> sImageID = null;
//***************************************//
SeekBar seekbar;
AudioManager audioManager;
MediaPlayer media, mediaPlayer;
boolean playPause = false;
boolean intialStage = true;
int intvalue ;
ImageView timer;
private static final int NOTIFICATION_ID = 1;
String URL = "http://streaming.shoutcast.com/MUKILFMRADIO";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addNotification();
mSmallBang = SmallBang.attach2Window(this);
list_activity_check = (ImageView) findViewById(R.id.list_view);
share = (ImageView) findViewById(R.id.share);
speaker = (ImageView) findViewById(R.id.speaker);
mute = (ImageView) findViewById(R.id.mute);
control = (ImageView) findViewById(R.id.play);
timer = (ImageView) findViewById(R.id.timer);
//************ Current show ************//
db = this.openOrCreateDatabase("MukilApp",Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS proname(ID INTEGER PRIMARY KEY AUTOINCREMENT,ImageID INTEGER,Title TEXT,FromTiming INTEGER,ToTiming INTEGER);");
rowItems = new ArrayList<Program>();
for (int i = 0; i < titles.length; i++) {
Program item = new Program(images0[i], titles[i],fromtime[i],totime[i]);
rowItems.add(item);
}
db.execSQL("DELETE FROM proname;");
lvshow = (ListView) findViewById(R.id.lvshow);
// listView.setVisibility(View.INVISIBLE);
final ProgramAdapter adapter = new ProgramAdapter(this,rowItems, false);
for (int i = 0; i < adapter.getCount(); i++) {
Program rowItem = (Program) adapter.getItem(i);
iImageId = rowItem.getImageId();
sTitle = rowItem.getTitle();
sFrom = rowItem.getFromtime();
sTo = rowItem.getTotime();
db.execSQL("INSERT INTO proname (ImageID,Title,FromTiming,ToTiming) VALUES(" + iImageId + ",'" + sTitle + "','" + sFrom + "','" + sTo + "');");
}
final Cursor cView = db.rawQuery("SELECT * FROM proname WHERE FromTiming <= time('now', 'localtime')\n" + "" +
"AND ToTiming >= time('now', 'localtime')\n", null);
if (cView.getCount() > 0) {
sImageID = new ArrayList<String>();
iTitle = new ArrayList<String>();
sQuantity = new ArrayList<String>();
sQuantity1 = new ArrayList<String>();
while (cView.moveToNext()) {
sImageID.add(cView.getString(1));
iTitle.add(cView.getString(2));
sQuantity.add(cView.getString(3));
sQuantity1.add(cView.getString(4));
Adapadapter = new AdapAdapter(this, sImageID, iTitle, sQuantity, sQuantity1);
lvshow.setAdapter(Adapadapter);
}
}
//*************************************//
timer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
Intent slideactivity = new Intent(MainActivity.this, Timer_Activity.class);
Bundle bndlanimation =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animate1, R.anim.animate2).toBundle();
// startActivity(slideactivity, bndlanimation);
startActivityForResult(slideactivity, 1001,bndlanimation);
// finish();
}
});
}
});
media = MediaPlayer.create(this,R.raw.mukil_master_jingle);
media.start();
media.setLooping(true);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
if (intialStage) {
new Player()
.execute(URL);
}
intvalue = mediaPlayer.getAudioSessionId();
control.setBackgroundResource(R.drawable.pause);
control.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (playPause == false) {
control.setBackgroundResource(R.drawable.play);
mediaPlayer.stop();
new Player().cancel(true);
media.stop();
media.reset();
mediaPlayer.reset();
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.reset();
media.stop();
playPause = true;
} else {
control.setBackgroundResource(R.drawable.pause);
if (intialStage) {
new Player()
.execute(URL);
} else {
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
}
playPause = false;
}
}
});
speaker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speaker.setVisibility(View.INVISIBLE);
mute.setVisibility(View.VISIBLE);
media.setVolume(0, 0);
mediaPlayer.setVolume(0, 0);
speaker.setImageResource(R.drawable.speaker);
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
}
});
}
});
mute.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
speaker.setVisibility(View.VISIBLE);
mute.setVisibility(View.INVISIBLE);
media.setVolume(1, 1);
mediaPlayer.setVolume(1, 1);
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowTitleEnabled(false); // hide built-in Title
}
try {
seekbar = (SeekBar) findViewById(R.id.seekbar1);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
seekbar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
seekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
}
});
} catch (Exception e) {
e.printStackTrace();
}
listview_nav = (ListView) findViewById(R.id.listview_nav);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
drawerListAdapter = new DrawerListAdapter(MainActivity.this, Items, images);
listview_nav.setAdapter(drawerListAdapter);
listview_nav.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position == 0){
Intent in = new Intent(MainActivity.this,ShowList_Activity.class);
startActivity(in);
}else if(position == 1){
}
}
});
list_activity_check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list_activity_check.setImageResource(R.drawable.playlist);
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
Intent slideactivity = new Intent(MainActivity.this, EqualizerActivity.class);
slideactivity.putExtra("sessionvalue", intvalue);
Bundle bndlanimation =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animate1, R.anim.animate2).toBundle();
startActivity(slideactivity, bndlanimation);
}
});
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
share.setImageResource(R.drawable.share_icon);
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
}
});
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"https://play.google.com/store/apps/details?id=com.digitamatix.mukilfm");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "https://play.google.com/store/apps/details?id=com.digitamatix.mukilfm" + " Mukil FM shareApp");
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
});
PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
//INCOMING call
//do all necessary action to pause the audio
if(mediaPlayer!=null){//check mp
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
}
if(media!=null){//check mp
if(media.isPlaying()){
media.pause();
}
}
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
//Not IN CALL
//do anything if the phone-state is idle
if(mediaPlayer == null){//check mp
if(!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
if(media==null){//check mp
if(!media.isPlaying()){
media.start();
}
}
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
//A call is dialing, active or on hold
//do all necessary action to pause the audio
//do something here
if(mediaPlayer!=null){//check mp
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
}
if(media!=null){//check mp
if(media.isPlaying()){
media.pause();
}
}
}
super.onCallStateChanged(state, incomingNumber);
}
};//end PhoneStateListener
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
private void addNotification() {
NotificationCompat.Builder builder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.mukil)
.setContentTitle("MUKIL FM")
.setContentText("Smartah Kelunga Ungal MukilFm");
// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
class Player extends AsyncTask<String, Void, Boolean> {
private ProgressDialog progress;
#Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
Boolean prepared;
try {
mediaPlayer.setDataSource(params[0]);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
intialStage = true;
playPause = false;
control.setBackgroundResource(R.drawable.play);
mediaPlayer.stop();
mediaPlayer.reset();
}
});
mediaPlayer.prepare();
mediaPlayer.prepareAsync();
prepared = true;
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
Log.d("IllegarArgument", e.getMessage());
prepared = false;
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (progress.isShowing()) {
progress.cancel();
}
Log.d("Prepared", "//" + result);
mediaPlayer.start();
media.stop();
intialStage = false;
}
public Player() {
progress = new ProgressDialog(MainActivity.this);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
this.progress.setMessage("Buffering...");
media.start();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1001) {
String result=data.getStringExtra("result");
if(result.equalsIgnoreCase("STOP")){
onStop();
finish();
}else if(result.equalsIgnoreCase("Do Nothing")){
Toast.makeText(this, "Timer is not set", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onStop() {
super.onStop();
if(media != null){
// media.stop(); //Stops playback after playback has been stopped or paused
media.release(); //Releases resources associated with this MediaPlayer object
media = null;
}
if(mediaPlayer!= null){
// mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer= null;
}
}
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
// set title
alertDialogBuilder.setTitle("Exit");
// set dialog message
alertDialogBuilder
.setMessage("Do you really want to exit?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
MainActivity.this.finish();
mediaPlayer.release();
media.release();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
// super.onBackPressed();
}
}
please help me in fixing this issues..
Thank you in advance..
In your onStop() of your activity stop and release the media player.
Place the below code in your onStop():
#Override
public void onStop() {
super.onStop();
if(media != null){
media.stop(); //Stops playback after playback has been stopped or paused
media.release(); //Releases resources associated with this MediaPlayer object
media = null;
}
if(mediaPlayer!= null){
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer= null;
}
}
This is the proper way to stop media player.
Hope it helps:)
I have a ListView which lists audio recordings. When I click on one to play, it goes out the the internet and retrieves the audio and plays it. When it plays the scrolling locks up.
Once the MediaPlayerhas stopped I can scroll like normal. This isn't a thread issue because the MediaPlayer is playing on another thread.
This is the MediaPlayer AsyncTask:
private class PlayAudio extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
nowPlaying = true;
player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
if(isAdded()) {
stopAudio();
}
PvmUtils.longToast(context, getString(R.string.error_load_msg));
return false;
}
});
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
setButtonColors(2);
}
});
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopAudio();
sendPostMessageRead(new Callbacks.SendPostMessageReadCallback() {
#Override
public void sendPostMessageReadCallback(boolean gotMessageReadResponse) {
if (gotMessageReadResponse) {
MessageLog message = log.get(listPosition);
message.setMessageStatus("read");
if (message.isReply()) {
currentMetaTextView.setText("");
MyFcmListenerService.newMessages--;
ShortcutBadger.applyCount(context, MyFcmListenerService.newMessages);
}
} else {
Log.d(LOG_TAG, "sendPostMessageReadCallback returned false, error may have occurred");
}
}
});
}
});
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
//Uri uri = Uri.parse(Keys.getpvmURL() + "android/retrieveMessage?messageId=" + params[0]);
//player.setDataSource(params[0].replaceFirst("https","http"));
Uri uri = Uri.parse(params[0]);
Map<String, String> headers = new HashMap<>();
headers.put("authorisation", encryption.getID().toString());
player.setDataSource(context, uri, headers);
} catch (IOException e) {
e.printStackTrace();
stopAudio();
} try {
player.prepare();
} catch (IOException e) {
e.printStackTrace();
stopAudio();
}
player.start();
return null;
}
}
This is the clicklistener for the list item:
ListAdapter newAdapter = new ListAdapter(getActivity());
if (this.log == null) {
list.setAdapter(populateAdapter(newAdapter,new ArrayList<MessageLog>()));
} else {
list.setAdapter(populateAdapter(newAdapter,log));
}
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(LOG_TAG, Integer.toString(position));
if (log != null && position < log.size()) {
if (!nowPlaying && log.get(position).getUrl() != null) {
try {
stopAudio();
setButtonColors(0, currentPlaying);
// Show the play controls.
currentPlaying = position;
nowPlaying = true;
player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
listPosition = position;
currentButton = view;
Log.d(LOG_TAG, log.get(position).getUrl());
/*
MessagePlaybackDialogFragment playFrag = MessagePlaybackDialogFragment.newInstance(log.get(listPosition),
new Callbacks.OnPlaybackFinishedListener() {
#Override
public void onPlaybackDone() {
// TODO set as not new
}
});
playFrag.show(getFragmentManager(), "playFrag");*/
// MessagePlaybackDialogFragment playFrag = MessagePlaybackDialogFragment.newInstance(log.get(listPosition));
// playFrag.show(getFragmentManager(), "playFrag");
currentMetaTextView = (TextView) view.findViewById(R.id.voiceMessageMetaText);
currentPlayPauseImageView = (ImageView) view.findViewById(R.id.voiceMessagePlayPauseImage);
currentMessageBackground = (RelativeLayout) view.findViewById(R.id.voiceMessageRectangleBackground);
setButtonColors(1);
currentAudio = new PlayAudio().execute(log.get(listPosition).getUrl());
} catch (Exception e) {
stopAudio();
e.printStackTrace();
}
} else if (position == listPosition){
stopAudio();
} else if (nowPlaying){
stopAudio();
currentPlaying = position;
player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
listPosition = position;
currentButton = view;
Log.d(LOG_TAG, log.get(position).getUrl());
currentMetaTextView = (TextView) view.findViewById(R.id.voiceMessageMetaText);
currentPlayPauseImageView = (ImageView) view.findViewById(R.id.voiceMessagePlayPauseImage);
currentMessageBackground = (RelativeLayout) view.findViewById(R.id.voiceMessageRectangleBackground);
setButtonColors(0, currentPlaying);
setButtonColors(1);
currentAudio = new PlayAudio().execute(log.get(listPosition).getUrl());
}
}
}
});
Try prepareAsync instead, this is my code...
mp.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
mp.setDataSource(a.getUrl());
mp.prepareAsync();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
activityList.get(position).setDuration(mp.getDuration()/1000);
holder.playButton.clearAnimation();
mp.start();
}
});
I am trying to update two TextViews txtName and textEndName. When i debug sometimes it updates the text but rest of the time it does not works. Sometime it works but not not exactly what it is suppose to.What is the problem in the below given code ?
txtName = (TextView) findViewById(R.id.txtstarttag);
textEndName = (TextView) findViewById(R.id.txtendtag);
startSec = (TextView) findViewById(R.id.txtstartsecnd);
endSec = (TextView) findViewById(R.id.txtendsecnd);
btnplay = (ImageButton) findViewById(R.id.btnplay);
btnback = (Button) findViewById(R.id.btnback);
btnback.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((MyMixes) getParent()).goBack();
}
});
btnplay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
btnClick();
}
});
splitArray();
Thread t = new Thread()
{
public void run()
{
while (isDownloading)
{
if (Data.filenames != null && Data.filenames.size() >= (getIntent() .getExtras().getInt("index") + 1) && Data.filenames.get(getIntent().getExtras() .getInt("index")) != null)
{
try
{
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(Data.filenames.get(getIntent().getExtras().getInt("index")));
mediaPlayer.prepare();
mediaPlayer.start();
Timer t = new Timer();
handler.postDelayed(onEverySecond, 1000);
mediaPlayer.setOnCompletionListener(new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.seekTo(0);
}
});
boolean isPlaying = mediaPlayer.isPlaying();
if(!isPlaying){
mediaPlayer.pause();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
isDownloading = false;
}
}
}
}
};
t.start();
}
private Runnable onEverySecond=new Runnable()
{
public void run()
{
if (mediaPlayer.isPlaying())
{
for (int i = index; i < intervals.length; i++)
{
if (i != index && mediaPlayer.getCurrentPosition() > intervals[i])
{
index = i;
handler.dispatchMessage(handler.obtainMessage());
handler.postDelayed(onEverySecond, 1000);
break;
}
}
}
}
};
Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg) {
txtName.setText(arrName.get(index));
textEndName.setText(arrName.get(index+1));
super.handleMessage(msg);
}
};
public void splitArray()
{
strSplit = kggg.split("\n");// string array
intervals = new long[strSplit.length];
Time timer;
for (int j = 0; j < strSplit.length; j++)
{
split = strSplit[j];// string
split1 = split.split("-");// string array
arrName.add(split1[0]);
String timeq = split1[1];
String[] timed = timeq.split(":");
if(timed.length == 3)
{
timer = new Time(Integer.parseInt(timed[0].trim()), Integer.parseInt(timed[1].trim()), Integer.parseInt(timed[2].trim()));
intervals[j] = timer.getTime();
}
else if(timed.length == 2)
{
timer = new Time(0, Integer.parseInt(timed[0].trim()), Integer.parseInt(timed[1].trim()));
intervals[j] = timer.getTime();
}
else if(timed.length == 1)
{
timer = new Time(0, 0, Integer.parseInt(timed[0].trim()));
intervals[j] = timer.getTime();
}
}
for (int j = intervals.length-1; j >= 0 ; j--)
{
intervals[j] = intervals[j] - intervals[0];
}
}
public void btnClick()
{
k++;
k = k % 2;
startSong(k);
}
private void startSong(int i) {
if (i == 1) {
System.out.println("11111" + i);
btnplay.setImageResource(R.drawable.pause);
try {
System.out.println("start try chech------");
mediaPlayer.start();
} catch (Exception e) {
mediaPlayer.pause();
}
}
if (i == 0) {
btnplay.setImageResource(R.drawable.play);
mediaPlayer.pause();
System.out.println("00000" + i);
}
}
You shouldn't be doing this:
handler.dispatchMessage(handler.obtainMessage());
Try this instead:
handler.sendMessage(handler.obtainMessage());
EDIT: Added other things I noticed
I also see that in your Thread you have a loop while (isDownloading) and you set isDownloading to false in the finally block. This loop while never run more than once.
Also, you do
btnplay.setImageResource(R.drawable.play);
inside a thead. This isn't good. You need to do everything related to UI on the main (UI) thread.