I have a media player service that plays a music in background, and this service is called from an activity. Now when i ex. exit from that activity, and get back to it again, i want to see what is the status, what song is played etc.
Here is the code from my service:
public class MediaPlayerService extends Service implements
OnCompletionListener, OnClickListener {
MediaPlayer mediaPlayer;
String url;
int mediaPos, mediaMax, position;
boolean isShufle;
WeakReference<SeekBar> seekbar;
WeakReference<TextView> reciter, songTitle, songPos;
private WeakReference<ImageView> play, forward, backward;
ArrayList<Songs> songs;
Handler handler;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
// mediaPlayer = MediaPlayer.create(this,url);// raw/s.mp3
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
private void play(final int position) throws IllegalArgumentException,
SecurityException, IllegalStateException, IOException {
/*
* dialog = ProgressDialog.show(AlbumDetails.this, "",
* getString(com.darkovski.quran.R.string.buffering), true);
* dialog.setCancelable(true); dialog.show();
*/
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(songs.get(position).getLink());
// prepare track
mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
play.get().setImageResource(R.drawable.pause);
// play.setImageResource(R.drawable.pause);
// this is new
mediaPos = mp.getCurrentPosition();
mediaMax = mp.getDuration();
reciter.get().setText(songs.get(position).getRecitorName());
songTitle.get().setText(songs.get(position).getTitle());
songPos.get().setText((position + 1) + " of 114");
seekbar.get().setMax(mediaMax);
seekbar.get().setProgress(mediaPos);
handler.removeCallbacks(moveSeekBarThread);
handler.postDelayed(moveSeekBarThread, 100);
mp.start();
// dialog.dismiss();
}
});
// when truck finishes
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// if(shuffle)
try {
if (isShufle) {
play(new Random().nextInt(songs.size()));
} else {
if (position == songs.size())
play(0);
else
play(position + 1);
}
AlbumDetails.position += 1;
} 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();
}
}
});
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
url = intent.getStringExtra("url");
handler = new Handler();
position = intent.getIntExtra("position", -1);
forward = new WeakReference<ImageView>(AlbumDetails.forward);
backward = new WeakReference<ImageView>(AlbumDetails.backward);
play = new WeakReference<ImageView>(AlbumDetails.play);
play.get().setOnClickListener(this);
forward.get().setOnClickListener(this);
backward.get().setOnClickListener(this);
seekbar = new WeakReference<SeekBar>(AlbumDetails.seekbar);
reciter = new WeakReference<TextView>(AlbumDetails.reciter);
songTitle = new WeakReference<TextView>(AlbumDetails.songTitle);
songPos = new WeakReference<TextView>(AlbumDetails.songPos);
songs = AlbumDetails.songs;
seekbar.get().setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (fromUser && mediaPlayer.isPlaying()) {
mediaPlayer.seekTo(progress);
}
}
});
/*
* try { mediaPlayer.setDataSource(url); mediaPlayer.prepare();
* mediaPlayer.setOnCompletionListener(this); } 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(); } if (!mediaPlayer.isPlaying()) {
* mediaPlayer.start(); }
*/
try {
play(position);
} 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();
}
return START_STICKY;
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
stopSelf();
}
private Runnable moveSeekBarThread = new Runnable() {
public void run() {
if (mediaPlayer.isPlaying()) {
int mediaPos_new = mediaPlayer.getCurrentPosition();
int mediaMax_new = mediaPlayer.getDuration();
seekbar.get().setMax(mediaMax_new);
seekbar.get().setProgress(mediaPos_new);
handler.postDelayed(this, 100);
}
}
};
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.playeer_back:
try {
if (mediaPlayer != null)
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
if (position - 1 < 0) {
play(songs.size());
position = songs.size();
} else
play(position - 1);
} catch (IllegalArgumentException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (SecurityException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IllegalStateException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
break;
case R.id.playeer_forward:
try {
if (mediaPlayer != null)
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
play(position + 1);
position += 1;
} 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();
}
break;
case R.id.playeer_play:
if (mediaPlayer == null) {
try {
play(position);
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} else if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
play.get().setImageResource(R.drawable.pause);
} else if (mediaPlayer != null) {
mediaPlayer.start();
play.get().setImageResource(R.drawable.play_play);
}
// playFunction();
break;
}
}
}
And my activity code - onClick:
case R.id.playeer_play:
playbackServiceIntent
.putExtra("url", songs.get(position).getLink());
playbackServiceIntent
.putExtra("position", position);
startService(playbackServiceIntent);
break;
There are different methods to realize it.
Using LocalBroadcastManager
Using an application to track the status of your service, i.e Song name, length, ...
Using SharedPreferences
IMHO, I think using a LocalBroadcastManager is more cleaner.
- Send a broadcast message to the service
- When the service receives the message, let it broadcast its status.
Related
I have a code that working in every android version.
but in android 6 throws
IllegalStateException
when i am calling
mediaPlayer.prepare();.
first page is working very well, but when i scroll to another pages, some time working very well and some time it is throwing IllegalStateException and audio can't play.
it is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mp3_player);
pager = (ViewPager) findViewById(R.id.pager);
Bundle extras = getIntent().getExtras();
final int id = extras.getInt("ID");
auMp3 = id + "_1.mp3";
f = new File(DIR_DATABASE + auMp3);
Uri uri = Uri.parse(G.DIR_DATABASE + auMp3);
if (f.exists()) {
MediaPlayer mp = MediaPlayer.create(G.context, uri);
}
imgPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (f.exists()) {
if (mp.isPlaying()) {
imgPlay.setImageResource(R.drawable.iplay);
mp.pause();
} else if ( !mp.isPlaying()) {
imgPlay.setImageResource(R.drawable.ipause);
mp.start();
}
} else {
menu.download(auMp3);
}
}
});
adapter = new AuPagerAdapter(aue);
pager.setAdapter(adapter);
pager.setCurrentItem(aue.size());
OnPageChangeListener currentit = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
int i = aue.size() - arg0;
auMp3 = id + "_" + i + ".mp3";
f = new File(DIR_DATABASE + auMp3);
imgPlay.setImageResource(R.drawable.iplay);
mp.reset();
if (f.exists()) {
try {
mp.setDataSource(G.DIR_DATABASE + auMp3);
}
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 {
mp.prepareAsync();
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(G.context, "IllegalStateException", 1).show();
}
}
}
I am using a TextureView to play a video in a ListView. The TextureView itself works perfectly, however, if I press the home button and reenter the application a few times, the TextureView turns black (though the audio continues to play). If I exit and reenter again, the TextureView turns white (or maybe transparent, as white is the colour of my background).
Here is my code:
holder.instagramTextureView
.setSurfaceTextureListener(new SurfaceTextureListener() {
#Override
public void onSurfaceTextureUpdated(
SurfaceTexture surface) {
// TODO Auto-generated method stub
}
#Override
public void onSurfaceTextureSizeChanged(
SurfaceTexture surface, int width, int height) {
// TODO Auto-generated method stub
}
#Override
public boolean onSurfaceTextureDestroyed(
SurfaceTexture surface) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onSurfaceTextureAvailable(
SurfaceTexture surface, int width, int height) {
final Surface s = new Surface(surface);
try {
holder.mMediaPlayer = new MediaPlayer();
holder.mMediaPlayer.setDataSource(post
.getMedias().get(0)
.getMediaUrlVideomp4StandardRes());
holder.mMediaPlayer.setSurface(s);
holder.mMediaPlayer.prepare();
holder.instagramVideoVolume = 0f;
holder.mMediaPlayer.setVolume(
holder.instagramVideoVolume,
holder.instagramVideoVolume);
//holder.mMediaPlayer.setOnBufferingUpdateListener(this);
holder.mMediaPlayer
.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(
MediaPlayer mp) {
// To play:
mp.reset();
try {
mp.setDataSource(post
.getMedias()
.get(0)
.getMediaUrlVideomp4StandardRes());
mp.prepare();
} 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();
}
// <--- Here comes a call to
// "To Resize" which is shown
// right above this code
mp.start();
}
});
// holder.mMediaPlayer.setOnPreparedListener(this);
//holder.mMediaPlayer.setOnVideoSizeChangedListener(this);
holder.mMediaPlayer
.setAudioStreamType(AudioManager.STREAM_MUSIC);
holder.mMediaPlayer.start();
holder.instagramTextureView
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (holder.instagramVideoVolume == 1) {
holder.instagramVideoVolume = 0f;
holder.mMediaPlayer
.setVolume(
holder.instagramVideoVolume,
holder.instagramVideoVolume);
} else {
holder.instagramVideoVolume = 1f;
holder.mMediaPlayer
.setVolume(
holder.instagramVideoVolume,
holder.instagramVideoVolume);
}
}
});
} 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();
}
}
});
Problem was making a new mediaplayer each time the surface is available. Not quite sure how this worked, but this was the problem. Instead, I create the mediaplayer outside of this listener.
From my research, textureView.getSurfaceTexture() returns null onResume(). What I did was reattach a listener to it in onResume().
TextureView textureView;
/*....
Usual stuff
*/
public void onPause(){
super.onPause();
//... destroy or disable image producer
}
public void onResume(){
super.onResume();
textureView.setSurfaceTextureListener(/*another listener*/);
}
Then, perform your usual things on onSurfaceTextureAvailable()
The black screen and audio playing happened with me when I did not release the MediaPlayer object.
Well I am a bit confused with the following.
I have a class (Main Player UI) that has the mediaplayer object.
Now the problem is that I want the music to played even after the UI has been disposed, hence I have to depend on the service.
But then if I move the MediaPlayer to the Service class
How am I going to control the onCompletion(MediaPlayer arg0) when the player UI is shown up, which also needs to show the change in the song? But then the method has to be included in the Service method.
How do I make the Play buttons on the UI to start the song that is available in the Service method?
Please guide me. The current player class that holds the UI as well as the mediaplayer is as follows:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_boombastic_player);
//INITIALIZATIONS
mMediaPlayer=new MediaPlayer();
utils = new Utilities();
songProgressBar=(SeekBar)findViewById(R.string.seeker);
play=(Button)findViewById(R.string.play);
next=(Button)findViewById(R.string.next);
previous=(Button)findViewById(R.string.previous);
playlist=(Button)findViewById(R.string.Playlist);
search=(Button)findViewById(R.string.search);
repeat=(Button)findViewById(R.string.repeat);
shuffle=(Button)findViewById(R.string.shuffle);
starttime=(TextView)findViewById(R.string.startTime);
endtime=(TextView)findViewById(R.string.endTime);
ObjectIntermediate=new Intermediate();
srvMplayer=new ServiceMan();
//Preparation
if(!Searched)
{
GetAllSongs();
Searched=true;
ShowToast("Finished Search");
}
songProgressBar.setOnSeekBarChangeListener(this); // Important
mMediaPlayer.setOnCompletionListener(this);
play.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
// check for already playing
if(mMediaPlayer.isPlaying())
{
if(mMediaPlayer!=null)
{
mMediaPlayer.pause();
/* Release Service*/
// Changing button image to play button
play.setBackgroundResource(R.drawable.playback_play);
}
}
else
{
// Resume song
if(mMediaPlayer!=null)
{
mMediaPlayer.start();
/* Starting Service*/
// Changing button image to pause button
play.setBackgroundResource(R.drawable.pause);
}
}
}
});
next.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
// check if next song is there or not
if(isRepeat)
{
playSong(currentSongIndex);
}
else if(isShuffle)
{
ShuffleSong();
playSong(currentSongIndex);
}
else if(currentSongIndex < (BoombasticPlayer.Songslist.size() - 1))
{
try
{
ShowToast(Integer.toString(currentSongIndex));
playSong(currentSongIndex + 1);
}
catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
Log.e("~~IllegalArgumentException~~",e.toString());
android.util.Log.e("->>" , "~~stacktrace~~", e);
}
catch (IllegalStateException e)
{
// TODO Auto-generated catch block
Log.e("~~IllegalStateException~~",e.toString());
android.util.Log.e("->>" , "~~stacktrace~~", e);
}
currentSongIndex = currentSongIndex + 1;
}
else
{
// play first song
try
{
playSong(0);
}
catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
Log.e("~~IllegalArgumentException~~",e.toString());
android.util.Log.e("->>" , "~~stacktrace~~", e);
}
catch (IllegalStateException e)
{
// TODO Auto-generated catch block
Log.e("~~IllegalStateException~~",e.toString());
android.util.Log.e("->>" , "~~stacktrace~~", e);
}
currentSongIndex = 0;
}
}
});
previous.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(isRepeat)
{
playSong(currentSongIndex);
}
else if(currentSongIndex > 0)
{
try {
playSong(currentSongIndex - 1);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
currentSongIndex = currentSongIndex - 1;
}
else
{
// play last song
try {
playSong(BoombasticPlayer.Songslist.size() - 1);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
currentSongIndex = BoombasticPlayer.Songslist.size() - 1;
}
}
});
playlist.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
Intent playlistIntent= new Intent(arg0.getContext(), Playlist.class);
startActivityForResult(playlistIntent, MODE_APPEND);
}
});
repeat.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(isRepeat==true)
{
isRepeat=false;
ShowToast("Repeat OFF");
}
else
{
isRepeat=true;
ShowToast("Repeat ON");
}
}
});
shuffle.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(isShuffle==true)
{
isShuffle=false;
ShowToast("Shuffle OFF");
}
else
{
isShuffle=true;
ShowToast("Shuffle ON");
}
}
});
}
I'm using media player. I want to show progress bar while connection URL and media player get prepare, but I can't show it.
public class MainActivity extends Activity implements OnClickListener, Runnable{
MediaPlayer mPlayer;
ProgressBar pBar = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Continue();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void Connect()
{
try {
Toast.makeText(getApplicationContext(),"Yayın Açılana Kadar Lütfen Bekleyiniz" , Toast.LENGTH_SHORT).show();
mPlayer.prepare();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
mPlayer.start();
pBar.setVisibility(ProgressBar.VISIBLE);
pBar.setProgress(0);
pBar.setMax(mPlayer.getDuration());
new Thread(this).start();
if(mPlayer!=null)pBar.setVisibility(ProgressBar.GONE);
}
public void Continue()
{
mPlayer = new MediaPlayer();
String str = "http:MyURL";
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mPlayer.setDataSource(str);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
Connect();
}
public void run() {
// TODO Auto-generated method stub
int currentPosition =0;
int total = mPlayer.getDuration();
while(mPlayer!=null && currentPosition<total){
try{
Thread.sleep(1000);
currentPosition = mPlayer.getCurrentPosition();
}catch(InterruptedException e){
return;
}catch(Exception e){
return;
}
pBar.setProgress(currentPosition);
}
}
}
You are calling pBar.setVisibility(ProgressBar.GONE); right after starting the thread..it will show and then disappear immediately..
Move it in the run method after the processing is done.
I am streaming mp3 on media-player, it plays continuos when your screen is on or you are doing multitasking but when you turn off screen it won't play audio continuously, it stucks many times.And I got this "info/warning (702,0) "on log cat
I tried mp.setWakeMode(getBaseContext(),PowerManager.FULL_WAKE_LOCK);
I am using service to play audio streaming but still it stucks.
public class myPlayService extends Service{
MediaPlayer mp;
String link ="http://85.23.194.72:70/mp3/str";
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
mp = new MediaPlayer();
try {
mp.setDataSource(link);
mp.setWakeMode(getBaseContext(),PowerManager.FULL_WAKE_LOCK);
mp.prepareAsync();
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.start();
}
});
} 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();
}
}#Override public void onDestroy() { mp.stop();mp.release();}}