I am trying to make a service that plays in background which is unbounded. I have walked myself through some of the example codes on the internet but I can't get my application to play the radio when I'm calling the service class.
Please have a look at the code and tell me where I am going wrong... When I call MyService class from ArmanFMRadio onClick It toasts "My Service Created" & "My Service Started" but doesnt get to play the audio for the radio stream link. I've checked it otherwise and the link seems fine, so problem lies somewhere in the code to my understanding:
package com.etc.etcc;
public class ArmanFMRadio extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.armanfm);
initializeUIElements();
//initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("http://50.117.26.26:3953/Live");
} 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();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setVisibility(View.VISIBLE);
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonPlay:
playSeekBar.setVisibility(View.VISIBLE);
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
startService(new Intent(this, MyService.class));
//startPlaying();
break;
case R.id.buttonStopPlay:
stopPlaying();
break;
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
Just look at onClick on the above code, because this class works fine to my thinking.
MyService class:
package com.etc.etcc;
public class MyService extends Service {
private static final String TAG = "MyService";
private 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");
}
#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 = new MediaPlayer();
try {
player.setDataSource("http://50.117.26.26:3953/Live");
} 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();
}
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
}
onStart is deprecated method. you should use onStartCommand method.
Debug your code and check weather there is any Exception or something
Also you are using the service so possible that you service will call twice in that case your onStartCommand method will be called twice so there you will have to check the startId which you will get as a parameter. If startId > 1 that means previously your service is started so you can stop media player and again start a media player with latest source or you can just ignore the second request.
If you are not confidence with service you can put your code in the activity and check weather your code is working fine or not after that you can replace this code in the service.
Related
I am developing an android app which play a mp3 songs by using a remote url. everything is working fine in android devices below api 5.0.But when starting app in samsung s5(5.1) it suddenly crashes
mu logcat is giving error "QCmediaPlayer mediaplayer is not present.Here is my code of Media Player
public class MainActivity2 extends Activity implements OnClickListener, OnPreparedListener {
private ProgressBar playSeekBar;
private final static String RADIO_STATION_URL ="https://aryaradio.s3.amazonaws.com/";
private String KEYNAME,encodedurl;
private List<String> playlistarray;
private List<MediaPlayer> mplayerList;
private ImageButton buttonPlay;
private List<S3ObjectSummary> playlist=null;
private ImageButton buttonStopPlay;
ProgressDialog progress;
URL url,currentsongurl;
private MediaPlayer player;
private AmazonS3Client mClient;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
playlistarray=new ArrayList<String>();
mplayerList=new ArrayList<MediaPlayer>();
if(isNetworkAvailable()) {
mClient = Util.getS3Client(MainActivity2.this);
initializeUIElements();
//new RefreshTask().execute();
buttonStopPlay.setVisibility(View.INVISIBLE);
} else {
new AlertDialog.Builder(MainActivity2.this)
.setTitle(getResources().getString(R.string.app_name))
.setMessage(
getResources().getString(
R.string.internet_error))
.setPositiveButton("OK", null).show();
buttonStopPlay.setVisibility(View.INVISIBLE);
buttonPlay.setVisibility(View.INVISIBLE);
}
}
private void initializeUIElements() {
buttonPlay = (ImageButton) findViewById(R.id.Play);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (ImageButton) findViewById(R.id.Stop);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
finish();
startActivity(new Intent(MainActivity2.this, MainActivity2.class));
}
}
private void startPlaying() {
buttonPlay.setVisibility(View.INVISIBLE);
buttonStopPlay.setVisibility(View.VISIBLE);
progress = new ProgressDialog(this);
progress.setTitle("Message");
progress.setMessage("Loading Song ...");
progress.setCancelable(true);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.show();
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
progress.dismiss();
player.start();
player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
try {
// player.setNextMediaPlayer(mplayerList.get(2));
stopPlaying();
} 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();
}
}
});
}
});
}
private void stopPlaying() {
killMediaPlayer();
initializeMediaPlayer(playlistarray);
buttonPlay.setVisibility(View.VISIBLE);
buttonStopPlay.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer(List<String> playlist) {
player = new MediaPlayer();
int noOfSongs=playlist.size();
String url = "https://aryaradio.s3.amazonaws.com/us-east-1:eb604ac1-c4e3-4226-bea8-22f214a6b0b0/RecordingArya-9459.mp3.null";
try {
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(url);
player.setOnPreparedListener(this);
player.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
return false;
}
});
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.i("Buffering", "" + percent);
}
});
}
}
My app breaks down when I attempt to record a second a time when I hit the stop button. I went through this code several times. I can't find the problem. I'm not sure if its my MediaRecorder or my MediaPlayer. It works the first time around. But not the second time. can anyone find the problem.
public class PatientName extends Activity implements OnClickListener {
private Button instructionsBtn;
private ImageView record;
private ImageView stop;
private MediaPlayer instructions;
private MediaPlayer namePlayer;
private MediaRecorder nameRecorder;
private String OUTPUT_FILE;
private Button play;
private Button accept;
private LinearLayout review;
private Button delete;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.patient_name);
OUTPUT_FILE = Environment.getExternalStorageDirectory() + "/namerecording.3gpp";
initializeViews();
initializeListeners();
}
public void initializeViews() {
instructionsBtn = (Button)findViewById(R.id.patient_name_instructions);
record = (ImageView)findViewById(R.id.record_name);
stop = (ImageView)findViewById(R.id.stop_name);
stop.setVisibility(View.GONE);
play = (Button)findViewById(R.id.play_name);
play.setVisibility(View.GONE);
review = (LinearLayout)findViewById(R.id.review_name);
delete = (Button)findViewById(R.id.delete_name);
accept = (Button)findViewById(R.id.accept_name);
review.setVisibility(View.GONE);
}
public void initializeListeners() {
instructionsBtn.setOnClickListener(this);
record.setOnClickListener(this);
stop.setOnClickListener(this);
play.setOnClickListener(this);
delete.setOnClickListener(this);
accept.setOnClickListener(this);
}
#Override
public void onBackPressed() {
}
public void playInstructions() {
setMaxVolume();
instructions = MediaPlayer.create(PatientName.this, R.raw.intro_instructions);
instructions.start();
instructions.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer play) {
instructions.release();
instructionsBtn.setEnabled(true);
}
});
}
public void setMaxVolume() {
AudioManager audio = (AudioManager) getSystemService(this.AUDIO_SERVICE);
int maxVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
audio.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, 0);
}
public void onClick(View v) {
int id = v.getId();
if (id==R.id.patient_name_instructions) {
instructionsBtn.setEnabled(false);
playInstructions();
}
if (id==R.id.record_name) {
beginRecording();
}
if (id==R.id.stop_name){
play.setVisibility(View.VISIBLE);
nameRecorder.stop();
}
if (id==R.id.play_name) {
playbackRecording();
}
if (id==R.id.delete_name){
deleteRecording();
}
if (id==R.id.accept_name) {
saveAndContinue();
}
}
private void beginRecording(){
record.setVisibility(View.GONE);
stop.setVisibility(View.VISIBLE);
File outFile = new File(OUTPUT_FILE);
if (outFile.exists()) {
outFile.delete();
}else {
nameRecorder = new MediaRecorder();
nameRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
nameRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
nameRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB);
nameRecorder.setOutputFile(OUTPUT_FILE);
try {
nameRecorder.prepare();
} catch (IllegalStateException e) {
Toast toast = Toast.makeText(this,"Illegal State",Toast.LENGTH_LONG);
toast.show();
e.printStackTrace();
} catch (IOException e) {
Toast toast = Toast.makeText(this,"Error Recording",Toast.LENGTH_LONG);
toast.show();
e.printStackTrace();
}
nameRecorder.start();
}
}
private void playbackRecording() {
play.setVisibility(View.GONE);
namePlayer = new MediaPlayer();
try {
namePlayer.setDataSource(OUTPUT_FILE);
} 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 {
namePlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
namePlayer.start();
namePlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer play) {
namePlayer.release();
nameRecorder.release();
review.setVisibility(View.VISIBLE);
}
});
}
private void deleteRecording() {
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
private void saveAndContinue() {
Intent intent = new Intent(PatientName.this, PatientLocation.class);
startActivity(intent);
}
}
Here is my logCat:
I figured out the issue. In the beginRecording method, I have an if and else statement that handles the output file. Unfortunately, the code that I had in the else statement was something that I wanted to always run no matter what.
In android, I have a mediaplayer on detail screen, which duplicates when I select another screen then play another detail, causing sound files to play on the same time. how do I fix this problem? Id like to play the most recent selected media only.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feeddetail);
tc_recDurat = (TextView)findViewById(R.id.recDetDurat);
tc_recDuratBack = (TextView)findViewById(R.id.recDetDuratBack);
TextView tc_recPath = (TextView)findViewById(R.id.recDetPath);
recPath = (String) intent.getSerializableExtra("INTENT_PATH");
tc_recPath.setText(recPath);
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(recPath);
} catch (IOException e1) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), e1.getLocalizedMessage(), Toast.LENGTH_LONG);
}
ImageButton mClickButton1 = (ImageButton)findViewById(R.id.btnPlay);
mClickButton1.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mediaPlayer !=null){
try {
mediaPlayer
mediaPlayer.prepare();
seekBar.setMax(mediaPlayer.getDuration());
mediaPlayer.start();
seekUpdate();
isPlaying = true;
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
ImageButton mClickButton2 = (ImageButton)findViewById(R.id.btnStop);
mClickButton2.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mediaPlayer.stop();
isPlaying = false;
}
});
I am not sure what your problem is, but i believe you are trying to say that as you change through different activities, the sounds files do not stop playing
In that case you can do the following
In the activity
You can override the onPause method and put mediaPlayer.stop() inside it
#Override
public void onPause() {
super.onPause();
mediaPlayer.stop();
}
I am developing one application where i want to play live stream radio. I have an url using which i will stream the radio and play. I have a play button by clicking which i want to play the radio. For that, i have written some code which is not at all working. Here is my code:
mp = new MediaPlayer();
try {
mp.setOnPreparedListener(this);
Log.d("Testing", "start111");
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
String url="xxxxxx";
mp.setDataSource(url);
mp.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
Log.d("Testing", "Exception ::: 1111 "+e.getMessage());
} catch (IllegalStateException e) {
Log.d("Testing", "Exception ::: 2222 "+e.getMessage());
e.printStackTrace();
} catch (IOException e) {
Log.d("Testing", "IOException ::: 3333 "+e.getMessage());
e.printStackTrace();
}
Can anyone please help me??
You can find good information regarding radio streaming.
Github radio streaming example
and also there is a question in SOF which can also be helpful
Stackoverflow radio streaming example
Hope it will help. thanks
Try this.
public class RadioStream extends Activity {
private final static String stream = "http://bbcmedia.ic.llnwd.net/stream/bbcmedia_radio2_mf_p";
Button play;
MediaPlayer mediaPlayer;
boolean started = false;
boolean prepared = false;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio_stream);
play = (Button) findViewById(R.id.play);
play.setEnabled(false);
play.setText("Loading..");
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (started) {
mediaPlayer.pause();
started = false;
play.setText("Play");
} else {
mediaPlayer.start();
started = true;
play.setText("Pause");
}
}
});
new PlayTask().execute(stream);
}
#Override
protected void onPause() {
super.onPause();
/* if(started)
mediaPlayer.pause();*/
}
#Override
protected void onResume() {
super.onResume();
/*if(started)
mediaPlayer.start();*/
}
#Override
protected void onDestroy() {
super.onDestroy();
// mediaPlayer.release();
}
private class PlayTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
play.setEnabled(true);
play.setText("Play");
}
}
}
Please do try the code below and call the given method at the on create of your activity or at the onclick listener of your button. Remember to handle the stop and start button the imgV is an imageView for my button.
private MediaPlayer player;
private void startMediaPlayer() {
String url = "http:yoururl.com"; // your URL here
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(url);
} 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();
}
if(isPlaying){
try {
mediaPlayer.prepareAsync();
progress.setVisibility(View.VISIBLE);
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
}
mediaPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
}
});
}
boolean isPlaying = true;
private void startPlaying() {
isPlaying = true;
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
imgV.setImageResource(R.drawable.stop);
}
private void stopPlaying() {
if (mediaPlayer.isPlaying()) {
isPlaying = false;
mediaPlayer.stop();
mediaPlayer.release();
initializeMediaPlayer();
}
imgV.setImageResource(R.drawable.play);
}
I am doing an audio online streaming the audio is playing fine both in emulator and device. But the issue is when i make a call to my device simultaneously the streaming also playing. I need to pause and play the audio back while the call is coiming. Can u help how to handle that broadcasting.
public class BhajanStream extends Activity {
protected static final String TAG = null;
/** Called when the activity is first created. */
final String rs_bhajan_uri = "Media URL";
MediaPlayer mediaPlayer;
AudioManager audioManager;
Button bhajan_play;
Button bhajan_stop;
ImageView loadanim, effectbhajan;
AnimationDrawable loadanimation, effectanimation;
ProgressDialog dialog;
MusicServicePhoneStateListener mPhoneListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bhajan);
bhajan_play = (Button) findViewById(R.id.btn_play);
bhajan_stop = (Button) findViewById(R.id.btn_stop);
bhajan_stop.setVisibility(View.GONE);
loadanim = (ImageView) findViewById(R.id.loadeffectview);
effectbhajan = (ImageView) findViewById(R.id.bhajan_effect);
/*if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer= null;
}*/
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// mediaPlayer.reset();
bhajan_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo Info = conMan.getActiveNetworkInfo();
if (Info == null) {
Toast.makeText(BhajanStream.this, "POOR SIGNALS ",
Toast.LENGTH_LONG).show();
// startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
loadanim.setBackgroundResource(R.drawable.loader_1);
loadanim.setBackgroundResource(R.anim.loadanim);
loadanimation = (AnimationDrawable) loadanim
.getBackground();
loadanimation.isVisible();
effectbhajan.setBackgroundResource(R.drawable.effect_bhajan1);
effectbhajan.setBackgroundResource(R.anim.bhajaneffect);
effectanimation = (AnimationDrawable) effectbhajan
.getBackground();
bhajan_play.setBackgroundResource(R.drawable.bhajan_start);
bhajan_play.setVisibility(View.GONE);
bhajan_stop.setVisibility(View.VISIBLE);
loadanim.setVisibility(View.VISIBLE);
effectbhajan.setVisibility(View.VISIBLE);
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(rs_bhajan_uri);
} catch (IllegalArgumentException 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 {
mediaPlayer.prepareAsync();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
}
});
bhajan_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
if (mediaPlayer != null) {
bhajan_stop.setVisibility(View.GONE);
bhajan_play.setVisibility(View.VISIBLE);
mediaPlayer.stop();
loadanimation.stop();
effectanimation.stop();
loadanim.setVisibility(View.GONE);
effectbhajan.setVisibility(View.GONE);
}}
}
});
}
protected void onPreExecute() {
// UI work allowed here
loadanimation.start();
}
#Override
public void onBackPressed() {
// do something
if (mediaPlayer.isPlaying()) {
if (mediaPlayer != null) {
mediaPlayer.stop();
loadanimation.stop();
effectanimation.stop();
bhajan_stop.setVisibility(View.GONE);
bhajan_play.setVisibility(View.VISIBLE);
loadanim.setVisibility(View.GONE);
effectbhajan.setVisibility(View.GONE);
}
} else{
startActivity(new Intent(BhajanStream.this, SaiStreams.class));
finish();
}
}
private class MusicServicePhoneStateListener extends PhoneStateListener {
private boolean mResumeAfterCall = false;
#Override
public void onCallStateChanged(int state, String incoming_number) {
switch (state) {
case TelephonyManager.CALL_STATE_OFFHOOK:
case TelephonyManager.CALL_STATE_RINGING:
Log.i(TAG, "phone active, suspending music service");
mResumeAfterCall = mediaPlayer.isPlaying();
mediaPlayer.pause();
break;
case TelephonyManager.CALL_STATE_IDLE:
Log.i(TAG, "phone inactive, resuming music service");
if (mResumeAfterCall) {
mediaPlayer.start();
}
break;
default:
break;
}
}
}
public void onCreate(){
mPhoneListener = new MusicServicePhoneStateListener();
((TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE)).listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
public void onDestroy(){
mPhoneListener = new MusicServicePhoneStateListener();
((TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE)).listen(mPhoneListener, 0);
}
}
In your activity,you can register a phone state listener by calling public void listen (PhoneStateListener listener, int events) in the TelephonyManager class. See here. Also,You can call Context.getSystemService(Context.TELEPHONY_SERVICE) to get an instance of the TelephonyManager object.