In my app, I am using media player in service for playing a music file. It is working but eventually gets started itself after sometime, and music starts playing. I am not getting where is the problem. Below, I am posting my code:
Media Player Service
public class ChalisaService extends Service implements OnCompletionListener
{
static MediaPlayer mediaPlayer;
static int playerFlag = 0;
TelephonyManager tm;
ActivityManager actManager;
/**
* 0 for stop/pause
* 1 for play*/
@Override
public IBinder onBind(Intent intent)
{
return null;
}//onBind
@Override
public void onCreate()
{
super.onCreate();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.chalisa);
mediaPlayer.setVolume(100, 100);
mediaPlayer.setOnCompletionListener(this);
tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
tm.listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}//onCreate
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
if(mediaPlayer.isPlaying())
{
mediaPlayer.pause();
/*HanuAlarm.txtPlay.setText("Play");
HanuAlarm.btn_Play.setBackgroundResource(R.drawable.btnplay);*/
playerFlag = 0;
}//if
else
{
mediaPlayer.start();
/*HanuAlarm.txtPlay.setText("Pause");
HanuAlarm.btn_Play.setBackgroundResource(R.drawable.btnpause);*/
playerFlag = 1;
}//else
startForeground(0, null);
return playerFlag;
}//onStartCommand
@Override
public void onDestroy()
{
super.onDestroy();
/*//mediaPlayer.stop();
//mediaPlayer.release();
playerFlag = 0;
Log.v("Chalisa service", "on destroy called");*/
}//onDestroy
private PhoneStateListener mPhoneListener = new PhoneStateListener() {
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
if(mediaPlayer.isPlaying())
{
mediaPlayer.pause();
playerFlag = 0;
}//if
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
if(mediaPlayer.isPlaying())
{
mediaPlayer.pause();
playerFlag = 0;
}//if
break;
/**
* Nitish
* 26 Sep 2012, Wed
* 11:50 AM*/
case TelephonyManager.CALL_STATE_IDLE:
if(!mediaPlayer.isPlaying())
{
mediaPlayer.start();
playerFlag = 1;
}//if
default:
Log.d("Chalisa Service", "Unknown phone state=" + state);
}
}
};
public void onCompletion(MediaPlayer mp)
{
mp.stop();
mp.release();
playerFlag = 0;
stopSelf();
updateUI();
Log.v("Chalisa Service media player", "on completion listener called");
}
private void updateUI()
{
Intent in = new Intent("com.dzo.HanumanChalisaWithAudioAndAlarm.UPDATE_UI");
in.putExtra("Player_FLAG_VALUE", playerFlag);
getApplicationContext().sendBroadcast(in);
}
}//ChalisaService