I have created demo for media player in Android.I'm facing the problem while start to run my application.When my app is run song is playing but not playing the full song it just start and immediately finish means it just start activity and immediately goes to resume() state.And when song is get over the i again restart my activity song is not playing from beginning it start from middle.I'm facing this problem last 1 week and i don't understand how to solve it .Please can any one help me.Here is my code.Thanks in advanced.
public class Audio_Activity extends Activity
{
private MediaPlayer mp = null;
PhoneStateListener phListener;
int length;
SharedPreferences prefs;
ImageView imgVw;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.audio);
init();
imgVw.setImageResource(R.raw.teddy_two);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences. Editor prefsEdit = prefs.edit();
mp=MediaPlayer.create(Audio_Activity.this,R.raw.issaq_tera_by_vishu);
Log.e("Song is playing","in Mediya Player ");
mp.start();
mp.setLooping(false);
System.out.println("Media Plyer Is Start !!!");
prefsEdit.putBoolean("mediaplaying", true);
prefsEdit.commit();
btnChapter.setEnabled(false);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
// TODO Auto-generated method stub
mp.stop();
System.out.println("Media Plyer Is Complete !!!");
//mp.release();
prefsEdit.putBoolean("mediaplaying", false);
prefsEdit.commit();
btnChapter.setEnabled(true);
System.out.println("Music is over and Button is enable !!!!!!");
}
});
PhoneStateListener phoneStateListener = new PhoneStateListener()
{
#Override
public void onCallStateChanged(int state, String incomingNumber)
{
if (state == TelephonyManager.CALL_STATE_RINGING)
{
if(mp!=null)
{
setPlayerButton(true, false, true);
if(mp.isPlaying())
{
mp.pause();
}
}
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
}
super.onCallStateChanged(state, incomingNumber);
}
};
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null)
{
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
private void setPlayerButton(Boolean play, Boolean pause, Boolean stop){
btnStartStop.setEnabled(play);
if(play==true)
btnStartStop.setEnabled(true);
else
btnStartStop.setEnabled(false);
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
#Override
public void onPause()
{
super.onPause();
SharedPreferences. Editor prefsEdit = prefs.edit();
boolean isPlaying=prefs.getBoolean("mediaplaying",false);
if(isPlaying)
{
int position = mp.getCurrentPosition();
Log.e("Current ","Position -> " + position);
prefsEdit.putInt("mediaPosition", position);
prefsEdit.commit();
}
}
#Override
protected void onResume()
{
super.onResume();
System.out.println("Activity is Resume !!!");
boolean isPlaying=prefs.getBoolean("mediaplaying",false);
if(isPlaying)
{
int position = prefs.getInt("mediaPosition", 0);
mp.seekTo(position);
mp.start();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
super.onStop();
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
if(mp!= null)
{
if(mp.isPlaying())
{
mp.pause();
System.out.println("Media Player is Pause/Stop click on Back button on Emulator!!!");
}
}
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
the starting from middle of the song problem is because you store the current progress of song in SharedPreferences and then at onResume() you start the player from the progressed position that stored at SharedPreferences
It's better to register for OnPreapredListener via MediaPlayer.setOnPreaparedListener and after preparation you start your media playback.
Official guide:
http://developer.android.com/guide/topics/media/mediaplayer.html
Please try to use bellow code.
void play() {
mediaPlayer = MediaPlayer.create(
getApplicationContext(), R.raw.keytone);
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
}
private void pause()
{
mediaPlayer.release();
}
Related
Please I want to know how to set my MediaPlayer to playback continuously without stopping when activity screen rotates? The challenge I'm having now is that when playing is in progress and I happen to tilt the screen the music stops and will require another action to have it play again.
this is the part of which plays the music in my Activity
// setting up media players
public void play(View v) {
if (player == null) {
//then here, I sent the position of the chosen song in the intent extras.
//the get back the extra
int position = 0;
try{
position=getIntent().getIntExtra("soundfile",0);
}catch (Exception e)
{
e.printStackTrace();
}
String fileToPlay="song_"+position;
player = MediaPlayer.create(this, position);
Toast.makeText(this, "Hymn Tune Playing", Toast.LENGTH_SHORT ).show();
soundSeekBar = (SeekBar) findViewById(R.id.seekBar1);
soundSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser){
player.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
soundSeekBar.setProgress(player.getCurrentPosition());
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
player.getCurrentPosition();
}
});
player.setLooping(true);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
}
});
}
player.start();
Toast.makeText(this, "Playing Continues...", Toast.LENGTH_SHORT ).show();
soundThread = new Thread(this);
soundThread.start();
}
public void pause(View v) {
if (player != null) {
player.pause();
Toast.makeText(this, "Hymn Tune Paused", Toast.LENGTH_SHORT ).show();
}
}
public void stop(View v) {
stopPlayer();
}
private void stopPlayer() {
if (player != null) {
player.release();
player = null;
Toast.makeText(this, "Hymn Tune Stoped", Toast.LENGTH_SHORT ).show();
}
}
#Override
protected void onStop() {
super.onStop();
stopPlayer();
}
#Override
public void run() {
int currentPosition = 0;
int soundTotal = player.getDuration();
soundSeekBar.setMax(soundTotal);
while (player != null && currentPosition < soundTotal){
try {
Thread.sleep(300);
currentPosition = player.getCurrentPosition();
}
catch (InterruptedException soundException){
return;
}
catch (Exception otherException){
return;
}
soundSeekBar.setProgress(currentPosition);
}
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
You must move your playback code to background service, as those will run constantly while activity is stopped and restarted during tilting. Check out extensive guide to services here
https://developer.android.com/guide/components/services
Currently, I'm working on my simple android studio script, and I must use volume down while the mobile screen is locked.
Please, take a look at my script:
public class MainActivity extends AppCompatActivity {
public MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final BroadcastReceiver vReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
initAudio(getApplicationContext(), "https://www.w3schools.com/html/horse.mp3");
}
};
registerReceiver(vReceiver, new IntentFilter("android.media.VOLUME_CHANGED_ACTION"));
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
event.startTracking();
initAudio(getApplicationContext(), "https://www.w3schools.com/html/horse.mp3");
return true;
}
return super.onKeyDown(keyCode, event);
}
public void initAudio(final Context context, String url) {
if (mediaPlayer == null) {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
killMediaPlayer();
}
});
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Fail", Toast.LENGTH_LONG).show();
killMediaPlayer();
}
}
}
public void pauseAudio() {
if (!(mediaPlayer == null)) {
mediaPlayer.pause();
}
}
public void startAudio() {
if (!(mediaPlayer == null)) {
mediaPlayer.start();
}
}
public void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
What should I do to fix this issue? There are no errors, the script only works when I'm with my screen unlocked.
Can you help me with this?
Thank you very much.
this is my code, i am almost certain the problem is with the while loop.
public void start(View view) {
int currentPosition = 0;
player = MediaPlayer.create(this, R.raw.sound);
player.start();
int total = player.getDuration();
progressBar.setProgress(0);
progressBar.setMax(player.getDuration());
while (player != null && currentPosition < total) {
// try {
// Thread.sleep(500);
currentPosition = player.getCurrentPosition();
// } catch (InterruptedException e) {
// return;
// } catch (Exception e) {
// return;
// }
progressBar.setProgress(currentPosition);
}
}
public void stop(View view) {
player.stop();
}
whether or not i have the sleep intervals my result is the same; the sound starts playing but i cant stop it, and the progress bar doesn't move.
i would appreciate some help
I used this code in my app for using seekBar with MediaPlayer. It implements Runnable to keep the seekBar updating as the music plays. Take a look at the code:
public class MainActivity extends Activity implements Runnable,
OnClickListener, OnSeekBarChangeListener {
private SeekBar seekBar;
private Button startMedia;
private Button stopMedia;
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekBar = (SeekBar) findViewById(R.id.seekBar1);
startMedia = (Button) findViewById(R.id.button1);
stopMedia = (Button) findViewById(R.id.button2);
startMedia.setOnClickListener(this);
stopMedia.setOnClickListener(this);
seekBar.setOnSeekBarChangeListener(this);
seekBar.setEnabled(false);
}
public void run() {
int currentPosition = mp.getCurrentPosition();
int total = mp.getDuration();
while (mp != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
public void onClick(View v) {
if (v.equals(startMedia)) {
if (mp == null) {
mp = MediaPlayer.create(getApplicationContext(), R.raw.song2);
seekBar.setEnabled(true);
}
if (mp.isPlaying()) {
mp.pause();
startMedia.setText("play");
} else {
mp.start();
startMedia.setText("pause");
seekBar.setMax(mp.getDuration());
new Thread(this).start();
}
}
if (v.equals(stopMedia) && mp != null) {
if (mp.isPlaying() || mp.getDuration() > 0) {
mp.stop();
mp = null;
startMedia.setText("play");
seekBar.setProgress(0);
}
}
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
try {
if (mp.isPlaying() || mp != null) {
if (fromUser)
mp.seekTo(progress);
} else if (mp == null) {
Toast.makeText(getApplicationContext(), "Media is not running",
Toast.LENGTH_SHORT).show();
seekBar.setProgress(0);
}
} catch (Exception e) {
Log.e("seek bar", "" + e);
seekBar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
Thanks to: Sridhar Kulkarni
I want to update the changes when I uncheck and check the checkbox in the preference activity but when I press the back button it doesn't work. It only works when I close the activity and then open it
Main activity
public class MainActivity extends ActionBarActivity {
private ToggleButton togle;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
private ShakeListener mShaker;
MediaPlayer mp;
ImageView anime;
int p=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
anime = (ImageView) findViewById(R.id.Animation);
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
// device doesn't support flash
// Show alert message and close the application
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish(); }
});
alert.show();
return;}
getCamera();
togle = (ToggleButton) findViewById(R.id.ToggleButton01);
togle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean checked = ((ToggleButton) v).isChecked();
if (checked){
turnOffFlash();
}
else{
getCamera();
turnOnFlash();
}
}
});
SharedPreferences getprefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean stopshake = getprefs.getBoolean("checkbox", true);
if (stopshake == true ){
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
public void onShake()
{ if (!isFlashOn) {
Toast.makeText(MainActivity.this, "On" , Toast.LENGTH_SHORT).show();
getCamera();
turnOnFlash();
}
else{
turnOffFlash();
Toast.makeText(MainActivity.this, "Off" , Toast.LENGTH_SHORT).show();
} }
});
}
}
private void getCamera() {
// TODO Auto-generated method stub
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
} }
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
getCamera();
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
anime.setImageResource(R.drawable.anim);
anime.post(new Runnable() {
#Override
public void run() {
AnimationDrawable frameAnimation =
(AnimationDrawable) anime.getDrawable();
frameAnimation.start();
}
});
// changing button/switch image
}
}
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
isFlashOn = false;
anime.setImageResource(R.drawable.off);
// changing button/switch image
}
}
private void playSound() {
// TODO Auto-generated method stub
if(isFlashOn){
mp = MediaPlayer.create(MainActivity.this, R.raw.off1);
}else{
mp = MediaPlayer.create(MainActivity.this, R.raw.on1);
}
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent = new Intent(MainActivity.this, Prefsetting.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Preference activity
public class Prefsetting extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefset);
}
}
You access SharedPreferences in the onCreate() of your MainActivity, which is only called when that activity is created from scratch (i.e. when you first start your app). As you (presumably) navigate to and from your Prefsetting Activity fairly quickly, MainActivity is likely only in a paused or stopped state when it is resumed. Take a look at the diagram here to see what happens to Activity classes as they move into and out of the foreground.
You have a couple of options. Either place this:
#Override
public void onResume() {
super.onResume();
SharedPreferences getprefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean stopshake = getprefs.getBoolean("checkbox", true);
if (stopshake) {
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
public void onShake() {
if (!isFlashOn) {
Toast.makeText(MainActivity.this, "On" , Toast.LENGTH_SHORT).show();
getCamera();
turnOnFlash();
} else {
turnOffFlash();
Toast.makeText(MainActivity.this, "Off" , Toast.LENGTH_SHORT).show();
}
}
});
} else {
if (mShaker != null) {
mShaker.setOnShakeListener(null);
mShaker = null;
}
}
}
Into somewhere like onResume().
Or, use an EventBus like LocalBrodcastManager to update your Preferences when onPause() is called in your PreferenceActivity.
From the code snippet it appears that you never actually commit your changes to the SharedPreferences of the application. Somewhere in the code when that boolean is flipped you need to do something like this:
prefs.put("checkbox", currentBooleanState).commit();
I'm trying to create a service that will play music in the background, but when a song completes the nextone should be played but seems oncomplete listener is not called. Can anyone tell me where is the problem?
P.S. I don't get anything in logcat, and I dont get the log that should be shown when entering oncomplete listener.
Here is my code:
public class myPlayService extends Service implements OnCompletionListener,
OnPreparedListener, OnErrorListener, OnSeekCompleteListener,
OnInfoListener, OnBufferingUpdateListener {
private static final String TAG = "--";
public static MediaPlayer mediaPlayer = new MediaPlayer();
// songs
private static ArrayList<Songs> songs;
private static int position;
// Set up the notification ID
private static final int NOTIFICATION_ID = 1;
private boolean isPausedInCall = false;
private PhoneStateListener phoneStateListener;
private TelephonyManager telephonyManager;
// ---Variables for seekbar processing---
String sntSeekPos;
static int intSeekPos;
int mediaPosition;
int mediaMax;
// Intent intent;
private final Handler handler = new Handler();
private static int songEnded;
public static boolean serviceStarted=false;
public static final String BROADCAST_ACTION = "com.darkovski.quran.seekprogress";
// Set up broadcast identifier and intent
public static final String BROADCAST_BUFFER = "com.darkovski.quran.broadcastbuffer";
Intent bufferIntent;
Intent seekIntent;
// Declare headsetSwitch variable
private int headsetSwitch = 1;
// OnCreate
#Override
public void onCreate() {
Log.v(TAG, "Creating Service");
// android.os.Debug.waitForDebugger();
// Instantiate bufferIntent to communicate with Activity for progress
// dialogue
serviceStarted=true;
songs = new ArrayList<Songs>();
bufferIntent = new Intent(BROADCAST_BUFFER);
// ---Set up intent for seekbar broadcast ---
seekIntent = new Intent(BROADCAST_ACTION);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnInfoListener(this);
mediaPlayer.reset();
// Register headset receiver
registerReceiver(headsetReceiver, new IntentFilter(
Intent.ACTION_HEADSET_PLUG));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// get songs and position
songs = new ArrayList<Songs>();
songs = (ArrayList<Songs>) intent.getSerializableExtra("songs");
Log.v("--", songs.size() + " size!#$");
position = intent.getIntExtra("position", -1);
// ---Set up receiver for seekbar change ---
registerReceiver(broadcastReceiver, new IntentFilter(
Player.BROADCAST_SEEKBAR));
// Manage incoming phone calls during playback. Pause mp on incoming,
// resume on hangup.
// -----------------------------------------------------------------------------------
// Get the telephony manager
Log.v(TAG, "Starting telephony");
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
Log.v(TAG, "Starting listener");
phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
// String stateString = "N/A";
Log.v(TAG, "Starting CallStateChange");
switch (state) {
case TelephonyManager.CALL_STATE_OFFHOOK:
case TelephonyManager.CALL_STATE_RINGING:
if (mediaPlayer != null) {
pauseMedia();
isPausedInCall = true;
}
break;
case TelephonyManager.CALL_STATE_IDLE:
// Phone idle. Start playing.
if (mediaPlayer != null) {
if (isPausedInCall) {
isPausedInCall = false;
playMedia();
}
}
break;
}
}
};
// Register the listener with the telephony manager
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
// Insert notification start
initNotification();
mediaPlayer.reset();
// Set up the MediaPlayer data source using the strAudioLink value
if (!mediaPlayer.isPlaying()) {
try {
// Send message to Activity to display progress dialogue
sendBufferingBroadcast();
mediaPlayer.setDataSource(songs.get(position).getLink());
;
// Prepare mediaplayer
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
}
}
// --- Set up seekbar handler ---
setupHandler();
return START_STICKY;
}
// ---Send seekbar info to activity----
private void setupHandler() {
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 300); // 1 second
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
// // Log.d(TAG, "entered sendUpdatesToUI");
LogMediaPosition();
handler.postDelayed(this, 1000); // 2 seconds
}
};
private void LogMediaPosition() {
// // Log.d(TAG, "entered LogMediaPosition");
if (mediaPlayer.isPlaying()) {
mediaPosition = mediaPlayer.getCurrentPosition();
// if (mediaPosition < 1) {
// Toast.makeText(this, "Buffering...", Toast.LENGTH_SHORT).show();
// }
mediaMax = mediaPlayer.getDuration();
// seekIntent.putExtra("time", new Date().toLocaleString());
seekIntent.putExtra("counter", String.valueOf(mediaPosition));
seekIntent.putExtra("mediamax", String.valueOf(mediaMax));
seekIntent.putExtra("song_ended", String.valueOf(songEnded));
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);
}
};
// Update seek position from Activity
public void updateSeekPos(Intent intent) {
int seekPos = intent.getIntExtra("seekpos", 0);
if (mediaPlayer.isPlaying()) {
handler.removeCallbacks(sendUpdatesToUI);
mediaPlayer.seekTo(seekPos);
setupHandler();
}
}
// ---End of seekbar code
// If headset gets unplugged, stop music and service.
private BroadcastReceiver headsetReceiver = new BroadcastReceiver() {
private boolean headsetConnected = false;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// Log.v(TAG, "ACTION_HEADSET_PLUG Intent received");
if (intent.hasExtra("state")) {
if (headsetConnected && intent.getIntExtra("state", 0) == 0) {
headsetConnected = false;
headsetSwitch = 0;
// Log.v(TAG, "State = Headset disconnected");
// headsetDisconnected();
} else if (!headsetConnected
&& intent.getIntExtra("state", 0) == 1) {
headsetConnected = true;
headsetSwitch = 1;
// Log.v(TAG, "State = Headset connected");
}
}
switch (headsetSwitch) {
case (0):
headsetDisconnected();
break;
case (1):
break;
}
}
};
private void headsetDisconnected() {
stopMedia();
stopSelf();
}
// --- onDestroy, stop media player and release. Also stop
// phoneStateListener, notification, receivers...---
#Override
public void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
if (phoneStateListener != null) {
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_NONE);
}
// Cancel the notification
cancelNotification();
// Unregister headsetReceiver
unregisterReceiver(headsetReceiver);
// Unregister seekbar receiver
unregisterReceiver(broadcastReceiver);
// Stop the seekbar handler from sending updates to UI
handler.removeCallbacks(sendUpdatesToUI);
// Service ends, need to tell activity to display "Play" button
resetButtonPlayStopBroadcast();
}
// Send a message to Activity that audio is being prepared and buffering
// started.
private void sendBufferingBroadcast() {
// Log.v(TAG, "BufferStartedSent");
bufferIntent.putExtra("buffering", "1");
sendBroadcast(bufferIntent);
}
// Send a message to Activity that audio is prepared and ready to start
// playing.
private void sendBufferCompleteBroadcast() {
// Log.v(TAG, "BufferCompleteSent");
bufferIntent.putExtra("buffering", "0");
sendBroadcast(bufferIntent);
}
// Send a message to Activity to reset the play button.
private void resetButtonPlayStopBroadcast() {
// Log.v(TAG, "BufferCompleteSent");
bufferIntent.putExtra("buffering", "2");
sendBroadcast(bufferIntent);
}
#Override
public void onBufferingUpdate(MediaPlayer arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public boolean onInfo(MediaPlayer arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onSeekComplete(MediaPlayer mp) {
if (!mediaPlayer.isPlaying()) {
playMedia();
Toast.makeText(this, "SeekComplete", Toast.LENGTH_SHORT).show();
}
}
// ---Error processing ---
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
Toast.makeText(this,
"MEDIA ERROR NOT VALID FOR PROGRESSIVE PLAYBACK " + extra,
Toast.LENGTH_SHORT).show();
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
Toast.makeText(this, "MEDIA ERROR SERVER DIED " + extra,
Toast.LENGTH_SHORT).show();
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
Toast.makeText(this, "MEDIA ERROR UNKNOWN " + extra,
Toast.LENGTH_SHORT).show();
break;
}
return false;
}
#Override
public void onPrepared(MediaPlayer arg0) {
// Send a message to activity to end progress dialogue
sendBufferCompleteBroadcast();
playMedia();
}
#Override
public void onCompletion(MediaPlayer mp) {
// When song ends, need to tell activity to display "Play" button
position += 1;
mp.stop();
mp.release();
Log.v("--", "complete");
// stopMedia();
playMedia();
// stopSelf();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public static void pause() {
mediaPlayer.pause();
}
public static void resume(){
mediaPlayer.start();
}
public static void playMedia() {
if (!mediaPlayer.isPlaying()) {
try {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(songs.get(position).getLink());
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
try {
mediaPlayer.setDataSource(songs.get(position).getLink());
mediaPlayer.prepare();
mediaPlayer.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();
}
}
}
public static void nextSong() {
if (position + 1 == songs.size())
position = 0;
else
position += 1;
playMedia();
}
public static void prevSong() {
if (position - 1 >= 0)
position -= 1;
else
position = songs.size() - 1;
playMedia();
}
// Add for Telephony Manager
public void pauseMedia() {
// Log.v(TAG, "Pause Media");
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
}
public void stopMedia() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
// Create Notification
private void initNotification() {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.ic_launcher;
CharSequence tickerText = "Tutorial: Music In Service";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
notification.flags = Notification.FLAG_ONGOING_EVENT;
Context context = getApplicationContext();
CharSequence contentTitle = "Music In Service App Tutorial";
CharSequence contentText = "Listen To Music While Performing Other Tasks";
Intent notificationIntent = new Intent(this, Player.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText,
contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
// Cancel Notification
private void cancelNotification() {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
mNotificationManager.cancel(NOTIFICATION_ID);
}
}