How Music player work when we kill (swipe) the recent app - android

When I play the music and come on home the music is running, but when I kill the app music is restart. I want to run the music when I kill the app instead of it restarting.
Please help me.
My code is:----
MainActivity.java
public class MainActivity extends ActionBarActivity {
Context context;
private Button mPlay, mStop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlay = (Button) findViewById(R.id.button1);
mStop = (Button) findViewById(R.id.button2);
mPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent service = new Intent(MainActivity.this, Myservice.class);
startService(service);
}
});
mStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent name = new Intent(MainActivity.this, Myservice.class);
stopService(name);
}
});
}
}
And my service class is:---
public class Myservice extends Service implements
MediaPlayer.OnErrorListener{
private final IBinder mBinder = new ServiceBinder();
MediaPlayer mPlayer;
private int length = 0;
public Myservice() { }
public class ServiceBinder extends Binder {
Myservice getService()
{
return Myservice.this;
}
}
#Override
public IBinder onBind(Intent arg0){return mBinder;}
#Override
public void onCreate (){
super.onCreate();
mPlayer = MediaPlayer.create(this, R.raw.follow);
mPlayer.setOnErrorListener(this);
if(mPlayer!= null)
{
mPlayer.setLooping(true);
mPlayer.setVolume(100,100);
}
mPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int
extra){
onError(mPlayer, what, extra);
return true;
}
});
}
#Override
public int onStartCommand (Intent intent, int flags, int startId)
{
mPlayer.start();
return START_STICKY;
}
public void pauseMusic()
{
if(mPlayer.isPlaying())
{
mPlayer.pause();
length=mPlayer.getCurrentPosition();
}
}
public void resumeMusic()
{
if(mPlayer.isPlaying()==false)
{
mPlayer.seekTo(length);
mPlayer.start();
}
}
public void stopMusic()
{
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
#Override
public void onDestroy ()
{
super.onDestroy();
if(mPlayer != null)
{
try{
/*mPlayer.stop();
mPlayer.release();*/
Toast.makeText(getApplicationContext(), "ondestroy", 2000).show();
}finally {
mPlayer = null;
}
}
}
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
if(mPlayer != null)
{
try{
mPlayer.stop();
mPlayer.release();
}finally {
mPlayer = null;
}
}
return false;
}
}

Add the below method in your service and call the method when media starts playing. Foreground service are high priority service which are not killed by android system often, starting a foreground service needs a notification. you can manually stop foreground service by calling stopForeground(true). Please watch for basics of Media Playback State of Media Playback (Android Dev Summit 2015)
private static final String NOTIFICATION_ID = 91;
private void runAsForeground(){
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,
notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
Notification notification=new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentText("Media is playing")
.setContentIntent(pendingIntent).build();
startForeground(NOTIFICATION_ID, notification);
}

Related

Android - Music duration less than MediaPlayer duration

I am trying to make a basic music player with bound services. The problem is MP plays less time that track duration is. I compared the times when MP finished and saw what happens but can not figure out why. Can anyone help?
Here is my logcat when MP finished.
#Override
public void onCompletion(MediaPlayer mp) {
Toast.makeText(this, "Media Completed", Toast.LENGTH_SHORT).show();
Log.i("TEST", "TOTAL DUR: " + mp.getDuration() + " CURRENT DUR: " + mp.getCurrentPosition() + "");
}
I/TEST: TOTAL DUR: 193131 CURRENT DUR: 186932
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener{
private String msg = "Android : ";
private TextView tvTime;
private Button btnPlay, btnPause, btnRestart;
private LocalService mService;
private boolean mBound = false;
// ----- seekbar variables -----------
private SeekBar seekBar;
private int seekMax;
private boolean mBroadcastIsRegistered;
// ---- broadcast action and intent for fromuser seekbar
public static final String BROADCAST_SEEKBAR_FROMUSER = "ysfcyln.musicplayerdemo.send_seekbar_fromUser";
Intent mIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvTime = (TextView) findViewById(R.id.textView);
seekBar = (SeekBar) findViewById(R.id.seekBar);
btnPlay = (Button) findViewById(R.id.btn_play);
btnPause = (Button) findViewById(R.id.btn_pause);
btnRestart = (Button) findViewById(R.id.btn_restart);
seekBar.setOnSeekBarChangeListener(this);
btnPlay.setOnClickListener(this);
btnPause.setOnClickListener(this);
btnRestart.setOnClickListener(this);
Log.d(msg, "The onCreate() event");
Intent intent = new Intent(this, LocalService.class);
startService(intent);
// set up seekbar intent for broadcasting new position to service
mIntent = new Intent(BROADCAST_SEEKBAR_FROMUSER);
}
/** Called when the activity is about to become visible. */
#Override
protected void onStart() {
super.onStart();
Log.d(msg, "The onStart() event");
Intent intent = new Intent(this, LocalService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
/** Called when the activity has become visible. */
#Override
protected void onResume() {
// ---- register broadcast -----
goRegisterBroadcast();
super.onResume();
Log.d(msg, "The onResume() event");
}
/** Called when another activity is taking focus. */
#Override
protected void onPause() {
// ---- unregister broadcast ----
unRegisterBroadcast();
super.onPause();
Log.d(msg, "The onPause() event");
}
/** Called when the activity is no longer visible. */
#Override
protected void onStop() {
super.onStop();
Log.d(msg, "The onStop() event");
}
/** Called just before the activity is destroyed. */
#Override
public void onDestroy() {
super.onDestroy();
Log.d(msg, "The onDestroy() event");
Log.d("mbound value", mBound + "");
if (mBound) {
Intent intent=new Intent(this,LocalService.class);
stopService(intent);
unbindService(mConnection);
mBound = false;
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_play:
//do something
if (mBound)
mService.playSong2("http://www.mfiles.co.uk/mp3-downloads/edvard-grieg-peer-gynt1-morning-mood-piano.mp3");
break;
case R.id.btn_pause:
//do something
if (mBound)
mService.pauseSong();
break;
case R.id.btn_restart:
//do something
if (mBound)
mService.restartSong();
break;
default:
break;
}
}
/** Defines callbacks for service binding, passed to bindService() */
public ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
LocalService.LocalBinder binder = (LocalService.LocalBinder) service;
mService = binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
#Override
public void onBackPressed(){
// this moves to activity to the back of the stack, effectively pausing it
moveTaskToBack(true);
}
// ---- updating position of seekbar from service
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}
};
private void updateUI(Intent intent){
String counter = intent.getStringExtra("counter");
String mediamax = intent.getStringExtra("mediamax");
int seekProgress = Integer.parseInt(counter);
seekMax = Integer.parseInt(mediamax);
seekBar.setMax(seekMax);
seekBar.setProgress(seekProgress);
final int HOUR = 60*60*1000;
final int MINUTE = 60*1000;
final int SECOND = 1000;
int durationInMillis = seekMax;
int curVolume = seekProgress;
int durationHour = durationInMillis/HOUR;
int durationMint = (durationInMillis%HOUR)/MINUTE;
int durationSec = (durationInMillis%MINUTE)/SECOND;
int currentHour = curVolume/HOUR;
int currentMint = (curVolume%HOUR)/MINUTE;
int currentSec = (curVolume%MINUTE)/SECOND;
if(durationHour > 0){
tvTime.setText(" 1 = "+String.format("%02d:%02d:%02d/%02d:%02d:%02d",
currentHour,currentMint,currentSec, durationHour,durationMint,durationSec));
}else{
tvTime.setText(" 1 = "+String.format("%02d:%02d/%02d:%02d",
currentMint,currentSec, durationMint,durationSec));
}
}
// --- unregister receiver for seekbar ---
private void unRegisterBroadcast(){
if(mBroadcastIsRegistered){
try {
unregisterReceiver(broadcastReceiver);
mBroadcastIsRegistered = false;
} catch (Exception e){
e.printStackTrace();
}
}
}
// --- register receiver for seekbar ---
private void goRegisterBroadcast(){
registerReceiver(broadcastReceiver, new IntentFilter(mService.BROADCAST_ACTION));
mBroadcastIsRegistered = true;
}
// Override methods for seekbar on change listener
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser){
int seekPos = seekBar.getProgress();
mIntent.putExtra("seekpos", seekPos);
sendBroadcast(mIntent);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
LocalService.java
public class LocalService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener{
private MediaPlayer player;
public LocalService() {
}
// Returns the MyService instance
public class LocalBinder extends Binder {
public LocalService getService(){
return LocalService.this;
}
}
private IBinder mBinder = new LocalBinder();
// ---- SeekBar Variables --------------
int mediaPosition;
int mediaMax;
private final Handler handler = new Handler();
public static final String BROADCAST_ACTION = "ysfcyln.musicplayerdemo.seekprogress";
Intent seekIntent;
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
//throw new UnsupportedOperationException("Not yet implemented");
Log.i("Service Demo", "In onBind");
return mBinder;
}
/** Called when the service is being created. */
#Override
public void onCreate() {
super.onCreate();
Log.i("Service Demo", "Service Created");
player = new MediaPlayer();
initMusicPlayer();
// ----- Setup intent for seekbar -----------
seekIntent = new Intent(BROADCAST_ACTION);
// --- register for fromuser seekbar ----
registerReceiver(broadcastReceiver, new IntentFilter(MainActivity.BROADCAST_SEEKBAR_FROMUSER));
}
/** The service is starting, due to a call to startService() */
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//return super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
/** Called when The service is no longer used and is being destroyed */
#Override
public void onDestroy() {
// stop the seekbar handler from sending updates to UI
handler.removeCallbacks(sendUpdatesToUI);
// unregister receiver to user input from seekbar
unregisterReceiver(broadcastReceiver);
super.onDestroy();
Log.i("Service Demo", "Service Destroyed");
}
/** Called when all clients have unbound with unbindService() */
#Override
public boolean onUnbind(Intent intent) {
Log.i("Service Demo", "In onUnbind");
player.stop();
player.reset();
player.release();
return super.onUnbind(intent);
}
/** Called when a client is binding to the service with bindService()*/
#Override
public void onRebind(Intent intent) {
super.onRebind(intent);
}
// to initialize the media class
public void initMusicPlayer(){
player.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
}
#Override
public void onPrepared(MediaPlayer mp) {
//start playback
mp.start();
// ---- set up seekbar handler ----
setUpHandler();
}
// -------- Send seekbar info to Activity ------
private void setUpHandler(){
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000); // 1 Second
}
private Runnable sendUpdatesToUI = new Runnable() {
#Override
public void run() {
LogMediaPosition();
handler.postDelayed(this,1000); // 1 Second
}
};
private void LogMediaPosition(){
if(player.isPlaying()){
mediaPosition = player.getCurrentPosition();
mediaMax = player.getDuration();
seekIntent.putExtra("counter", String.valueOf(mediaPosition));
seekIntent.putExtra("mediamax", String.valueOf(mediaMax));
sendBroadcast(seekIntent);
}
}
// ---------- Receive seekbar position if it has been changed by the user in the activity ----
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateSeekPos(intent);
}
};
private void updateSeekPos(Intent intent){
int seekPos = intent.getIntExtra("seekpos", 0);
if(player.isPlaying()){
handler.removeCallbacks(sendUpdatesToUI);
player.seekTo(seekPos);
setUpHandler();
}
}
public void playSong(){
//play a song
player.reset();
String songUrl = "http://www.mfiles.co.uk/mp3-downloads/edvard-grieg-peer-gynt1-morning-mood-piano.mp3";
try{
player.setDataSource(getApplicationContext(), Uri.parse(songUrl));
}
catch(Exception e){
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
player.prepareAsync();
}
public void pauseSong(){
if(player.isPlaying()){
player.pause();
} else {
player.start();
}
}
public void restartSong(){
if(player.isPlaying()){
player.stop();
player.release();
} else {
player.release();
}
}
// With input
public void playSong2(String songUrl){
//play a song
player.reset();
try{
player.setDataSource(getApplicationContext(), Uri.parse(songUrl));
}
catch(Exception e){
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
player.prepareAsync();
}
#Override
public void onCompletion(MediaPlayer mp) {
Toast.makeText(this, "Media Completed", Toast.LENGTH_SHORT).show();
Log.i("TEST", "TOTAL DUR: " + mp.getDuration() + "CURRENT DUR: " + mp.getCurrentPosition() + "");
}
}
I tested it with two device, Samsung Galaxy A7 and Samsung Galaxy S4. Song Duration is 3:13, A7 finished it 3:12 and S4 finished it 3:06

How to Stop Service of Music Background?

I need a background music which is continuously playing through Activities. I want to stop my background music when clicking on the Home Button.
This is my Service Code.
public class BackgroundSoundService extends Service
{
private static final String TAG = null;
MediaPlayer player;
Context context;
private int length = 0;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.haha);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
#Override
public void onStart(Intent intent, int startId) {
player.start();
}
public IBinder onUnBind(Intent arg0) {
return null;
}
public void onStop() {
player.stop();
player.release();
player = null;
}
public void onPause() {
player.pause();
}
public void onHomePressed(){
player.stop();
}
public void pauseMusic()
{
if(player.isPlaying())
{
player.pause();
length=player.getCurrentPosition();
}
}
public void resumeMusic()
{
if(player.isPlaying()==false)
{
player.seekTo(length);
player.start();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if(player != null)
{
try{
player.stop();
player.release();
}finally {
player = null;
}
}
}
#Override
public void onLowMemory() {
}
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
if(player != null)
{
try{
player.stop();
player.release();
}finally {
player = null;
}
}
return false;
}
}
This is my 1st Activity Class
public class AdventureTime extends Activity implements OnClickListener {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.story);
Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);
View story1 = this.findViewById(R.id.button1);
story1.setOnClickListener(this);
View story2 = this.findViewById(R.id.button2);
story2.setOnClickListener(this);
View story3 = this.findViewById(R.id.button3);
story3.setOnClickListener(this);
View back= this.findViewById(R.id.buttonback);
back.setOnClickListener(this);
}
#Override
public void onBackPressed(){
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
System.exit(0);
}
}).setNegativeButton("No", null).show();
}
public void onClick(View v) {
switch(v.getId()){
case R.id.button1:
Intent button1 = new Intent(this, Story1.class);
startActivity(button1);
break;
case R.id.button2:
Intent button2 = new Intent(this, Story2.class);
startActivity(button2);
break;
case R.id.button3:
Intent button3 = new Intent(this, Story3.class);
startActivity(button3);
break;
case R.id.buttonback:
Intent buttonback = new Intent(this, MainActivity.class);
startActivity(buttonback);
break;
}
}
}
Add this in the Activity AdventureTime :
...
#Override
public void onPause(){
stopService(svc);
super.onPause();
}
...
if you want to pause music without stopping your service
try this
add this class in your service
public class LocalBinder extends Binder {
BackgroundSoundService getService() {
return BackgroundSoundService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final IBinder mBinder = new LocalBinder();
and add this in your activity
private BackgroundSoundService mBoundService;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mBoundService = ((BackgroundSoundService.LocalBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
mBoundService = null;
}
};
replace
startService(svc)
with
bindService(svc, mConnection, Context.BIND_AUTO_CREATE);
and call the pause method in service whenever u need it
mBoundService.pauseMusic();
Why don't you try to listen to a dispatchKeyEvent instead? You could write:
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_HOME) {
stopService(svc)
return true;
}
else
return super.dispatchKeyEvent(event);
}
on each of your activities.
on you mainActivity class add this.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_HOME) {
// pause or stop ung Background music here.
return true;
}
return false;
}

Android Music service in background

I have a problem here, I have a music track works in the background of an app that is never stop and when I add OnDestroy() or Pause() in my main activity class gives me an error when running the application not in the class and I don't know where to put them to control the music in the main !!
here are the codes that gives me an error:
mServ.pauseMusic();
mServ.resumeMusic();
mServ.stopMusic();
The Main Activity:
private boolean mIsBound = false;
private MusicService mServ;
private ServiceConnection Scon = new ServiceConnection(){
public void onServiceConnected(ComponentName name, IBinder binder) {
mServ = ((MusicService.ServiceBinder)binder).getService();
}
public void onServiceDisconnected(ComponentName name) {
mServ = null;
}
};
void doBindService(){
bindService(new Intent(this,MusicService.class),
Scon,Context.BIND_AUTO_CREATE);
mIsBound = true;
}
void doUnbindService()
{
if(mIsBound)
{
unbindService(Scon);
mIsBound = false;
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent music = new Intent();
music.setClass(this,MusicService.class);
startService(music);
And The Service Activity:
public class MusicService extends Service implements MediaPlayer.OnErrorListener {
private final IBinder mBinder = new ServiceBinder();
MediaPlayer mPlayer;
private int length = 0;
public MusicService(){}
public class ServiceBinder extends Binder {
public MusicService getService()
{
return MusicService.this;
}
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return mBinder;
}
public void onCreate(){
super.onCreate();
mPlayer = MediaPlayer.create(this, R.raw.la);
mPlayer.setOnErrorListener(this);
if(mPlayer != null){
mPlayer.setLooping(true);
mPlayer.setVolume(100, 100);
}
mPlayer.setOnErrorListener(new OnErrorListener(){
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
onError(mPlayer, what, extra);
return true;
}
});
}
public int onStartCommand (Intent intent , int flags, int startId)
{
mPlayer.start();
return START_STICKY;
}
public void pauseMusic()
{
if(mPlayer.isPlaying())
{
mPlayer.pause();
length=mPlayer.getCurrentPosition();
Toast.makeText(this, "Music is Paused", Toast.LENGTH_LONG).show();
}
}
public void resumeMusic()
{
if(mPlayer.isPlaying()==false)
{
mPlayer.seekTo(length);
Toast.makeText(this, "Music is started", Toast.LENGTH_LONG).show();
mPlayer.start();
}
}
public void stopMusic()
{
mPlayer.stop();
Toast.makeText(this, "Music is stoped", Toast.LENGTH_LONG).show();
mPlayer.release();
mPlayer = null;
}
#Override
public void onDestroy ()
{
super.onDestroy();
if(mPlayer != null)
{
try{
mPlayer.stop();
mPlayer.release();
}finally {
mPlayer = null;
}
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
Toast.makeText(this, "Music player failed", Toast.LENGTH_SHORT).show();
if(mPlayer != null)
{
try{
mPlayer.stop();
mPlayer.release();
}finally {
mPlayer = null;
}
}
return false;
}
}
The code is based on this link tutorial

MusicPlayer crashes on click the back button

I made a simple music player which can play some songs in the background.
Going to the homescreen and reopen the app through notification works as well.
The only Problem I have is that if I press the back button(going to parent activity) in the music player activity my app crashes. There are two classes, the activity MP3Player.java and the service MP3Service.jave.
I am getting the following error:
java.lang.RuntimeException: Unable to destroy activity {package/package.MP3Player}: java.lang.IllegalArgumentException: Service not registered: package.MP3Player$1#b135b300
Do you know any advide?
Thanks in advance!
EDIT1:
I bound my player like this in my player activity:
MP3Player.java(Activity)
playIntent = new Intent(this, MP3Service.class);
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
I used this tutorial and modified it.
EDIT 3:
Now I get this error:
java.lang.RuntimeException: Unable to stop service package.MP3Service#b13a6f80: java.lang.IllegalStateException
MP3Service.java
public void onCreate() {
super.onCreate();
songPosn = 0;
player = new MediaPlayer();
initMusicPlayer();
}
public void initMusicPlayer() {
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
...
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
public void setList(ArrayList<Song> theSongs) {
songs = theSongs;
}
public class MusicBinder extends Binder {
MP3Service getService() {
return MP3Service.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return musicBind;
}
#Override
public boolean onUnbind(Intent intent) {
player.stop();
player.release();
return false;
}
public void playSong() {
player.reset();
Song playSong = songs.get(songPosn);
try {
player.setDataSource(getApplicationContext(),
Uri.parse(playSong.getPath()));
} catch (Exception e) {
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
player.prepareAsync();
}
public void pauseMusic() {
if (player.isPlaying()) {
player.pause();
length = player.getCurrentPosition();
}
}
public void resumeMusic() {
if (player.isPlaying() == false) {
player.seekTo(this.length);
player.start();
} else {
Toast.makeText(getApplicationContext(),
"Please select a song to play", Toast.LENGTH_LONG).show();
}
}
public void stopMusic() {
player.stop();
player.release();
player = null;
}
// set the song
public void setSong(int songIndex) {
songPosn = songIndex;
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
#Override
public void onDestroy() {
super.onDestroy();
if (player != null) {
try {
player.stop();
player.release();
} finally {
player = null;
}
}
}
MP3Player.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mp3_player);
getActionBar().setDisplayHomeAsUpEnabled(true);
songList = getSongList();
listAdapter = new PlayListAdapter(this, songList);
listMusic.setAdapter(listAdapter);
listMusic.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos,
long arg3) {
currentSongPos = pos;
musicSrv.setSong(currentSongPos);
musicSrv.playSong();
}
});
}
private ServiceConnection musicConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicBinder binder = (MusicBinder) service;
musicSrv = binder.getService();
musicSrv.setList(songList);
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
#Override
protected void onStart() {
super.onStart();
if (playIntent == null) {
playIntent = new Intent(this, MP3Service.class);
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
}
}
...
protected void onDestroy() {
if (musicBound) {
stopService(playIntent);
unbindService(musicConnection);
musicSrv = null;
}
super.onDestroy();
}
Service not registered means it wasn't bound to service during unbindService() call.
Read about service lifecycle on : API Guide: Services
EDIT:
Try to add:
protected void onDestroy() {
if(musicBound){
stopService(playIntent);
unbindService(musicConnection);
musicSrv=null;
}
super.onDestroy();
}
EDIT 2:
Sorry my fault, you need to call first stopService() and then unbindService()
The Android documentation for stopService() states:
Note that if a stopped service still has ServiceConnection objects bound to it with the BIND_AUTO_CREATE set, it will not be destroyed
until all of these bindings are removed. See the Service documentation
for more details on a service's lifecycle.

Music player in Android (emulator)

I did a small simulation of background music play on Android, but it doesnt work... there's the code:
[my activity, in onCreate]
Intent music = new Intent(this, MusicService.class);
startService(music);
[and there's the class MusicService]
public class MusicService extends Service implements MediaPlayer.OnErrorListener {
private final IBinder mBinder = new ServiceBinder();
MediaPlayer mPlayer;
private int length = 0;
public class ServiceBinder extends Binder {
MusicService getService()
{
return MusicService.this;
}
}
#Override
public IBinder onBind(Intent arg0){
return mBinder;
}
#Override
public void onCreate () {
super.onCreate();
mPlayer = MediaPlayer.create(this, R.raw.song1);
mPlayer.setOnErrorListener(this);
if(mPlayer!= null)
{
mPlayer.setLooping(true);
mPlayer.setVolume(100,100);
}
mPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra){
onError(mPlayer, what, extra);
return true;
}
});
}
#Override
public int onStartCommand (Intent intent, int flags, int startId)
{
mPlayer.start();
return START_STICKY;
}
public void pauseMusic()
{
if(mPlayer.isPlaying())
{
mPlayer.pause();
length=mPlayer.getCurrentPosition();
}
}
public void resumeMusic()
{
if(mPlayer.isPlaying()==false)
{
mPlayer.seekTo(length);
mPlayer.start();
}
}
public void stopMusic()
{
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
#Override
public void onDestroy ()
{
super.onDestroy();
if(mPlayer != null)
{
try{
mPlayer.stop();
mPlayer.release();
}
finally {
mPlayer = null;
}
}
}
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
if(mPlayer != null)
{
try{
mPlayer.stop();
mPlayer.release();
}
finally {
mPlayer = null;
}
}
return false;
}
}
I can't hear any song in the emulator. I did complete the Manifest file like this:
<service
android:name="MusicService"
android:enabled="true">
</service>
Is there something else to add to the Manifest, is there a problem with my code or with my emulator?
Thank you!
I am shearing my code on background music play on Android. It will be solve your problem.
I head created two classes first one is MainActivity and second one is MyService.
MainActivity code is
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "MainActivity";
Button play, stop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
play = (Button) findViewById(R.id.play);
stop = (Button) findViewById(R.id.stop);
play.setOnClickListener(this);
stop.setOnClickListener(this);
}
#Override
public void onClick(View src) {
switch (src.getId()) {
case R.id.play:
Log.d(TAG, "onClick: starting srvice");
startService(new Intent(this, MyService.class));
break;
case R.id.stop:
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
break;
}
}
}
Now the MyService code is
public class MyService extends Service {
private static final String TAG = "MyService";
MediaPlayer player;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
player = MediaPlayer.create(this, R.raw.braincandy);
player.setLooping(false); // Set looping
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
}
}
U have to create a "raw" folder in your "res" folder than paste your music file in that raw folder.

Categories

Resources