I coded a simple mp3 player a couple of days ago. The code is at Playing music in sleep/standby mode in Android 2.3.3
Everything works fine when the mp3 player (Samsung 3.6, Android 2.2) plays music on its own. I bought a bluetooth speaker (A2DP 3.0) and connected it to the mp3 player. The music still plays fine, but when the mp3 player screen goes dark into sleep mode, the music starts skipping on the bluetooth speaker.
It does not happen if the mp3 plays music on its own in sleep mode
Other music player apps in the mp3 player seem to play fine even in sleep mode over the bluetooth speaker
If I disable bluetooth, and play the music using the speaker connected by a cable, then the music plays fine even in standby mode.
This leads me to believe that something may be wrong with my code.
Here's my complete code:
public class MainActivity extends Activity {
private static String audioPath;
private static ArrayList<String> devotionalList;
private static ArrayList<String> christmasList;
private static ArrayList<String> cinemaList;
private static ImageButton playPauseButton;
private static TextView appMsg;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int maxVolume = audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
SeekBar volControl = (SeekBar) findViewById(R.id.volumeBar);
volControl.setMax(maxVolume);
volControl.setProgress(curVolume);
volControl
.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onProgressChanged(SeekBar arg0, int arg1,
boolean arg2) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
arg1, 0);
}
});
File baseDir = Environment.getExternalStorageDirectory();
audioPath = baseDir.getAbsolutePath() + "/external_sd/music/";
devotionalList = loadSongs(audioPath + "devotional/");
christmasList = loadSongs(audioPath + "christmas/");
cinemaList = loadSongs(audioPath + "cinema/");
}
private ArrayList<String> loadSongs(String songDirectory) {
File directory = new File(songDirectory);
ArrayList<String> al1 = new ArrayList<String>();
for (String filename : directory.list()) {
al1.add(songDirectory + filename);
}
return al1;
}
public void playPauseSong(View v) {
if (MP3PlayerService.isPlaying) {
playPauseButton.setImageResource(android.R.drawable.ic_media_play);
// Intent i1 = new Intent(this, MP3PlayerService.class);
stopService(new Intent(this, MP3PlayerService.class));
} else {
if (MP3PlayerService.playerStarted) {
playPauseButton
.setImageResource(android.R.drawable.ic_media_pause);
startService(new Intent(this, MP3PlayerService.class));
}
}
}
public void playNextSong(View v) {
if (MP3PlayerService.playerStarted) {
startService(new Intent(this, MP3PlayerService.class));
}
}
public void playPreviousSong(View v) {
if (MP3PlayerService.playerStarted) {
MP3PlayerService.previousSong = true;
startService(new Intent(this, MP3PlayerService.class));
}
}
#Override
protected void onPause() {
super.onPause();
playPauseButton = null;
appMsg = null;
}
#Override
protected void onResume() {
super.onResume();
appMsg = (TextView) this.findViewById(R.id.txtAppMsg);
appMsg.setText("");
playPauseButton = (ImageButton) this.findViewById(R.id.btnPlayPause);
}
public void playDevotional(View v) {
playPlayList(devotionalList);
}
public void playChristmas(View v) {
playPlayList(christmasList);
}
public void playCinema(View v) {
playPlayList(cinemaList);
}
private void playPlayList(ArrayList<String> playList) {
if (MP3PlayerService.isPlaying) {
MP3PlayerService.mediaPlayer.stop();
MP3PlayerService.mediaPlayer.reset();
MP3PlayerService.mediaPlayer.release();
}
MP3PlayerService.songPosition = 0;
playPauseButton.setImageResource(android.R.drawable.ic_media_pause);
Intent i1 = new Intent(this, MP3PlayerService.class);
i1.putExtra("playListChoice", playList);
startService(i1);
}
}
And here's my code for the mediaplayer service:
public class MP3PlayerService extends Service implements OnCompletionListener {
private static ArrayList<String> al1;
private static FileInputStream fis;
private static FileDescriptor fd;
static boolean previousSong;
static boolean playerStarted = false;
static int songPosition;
static boolean isPlaying = false;
static String currentSong;
static ArrayList<String> songHistory;
static MediaPlayer mediaPlayer;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
songHistory = new ArrayList<String>();
}
#Override
public void onDestroy() {
songPosition = mediaPlayer.getCurrentPosition();
mediaPlayer.pause();
isPlaying = false;
}
#Override
public void onStart(Intent intent, int startid) {
if (songPosition == 0) {
Bundle extras = intent.getExtras();
if (extras == null) {
if (previousSong) {
playSong();
} else {
// Next Song Button clicked
playNextSong();
}
} else {
// A Playlist button is clicked
al1 = (ArrayList<String>) extras.get("playListChoice");
playSong();
}
} else {
songPosition = 0;
mediaPlayer.start();
}
isPlaying = true;
}
private void playNextSong() {
if (isPlaying) {
mediaPlayer.release();
playSong();
}
}
private void playSong() {
if (previousSong) {
mediaPlayer.release();
if (songHistory.size() > 1) {
currentSong = songHistory.get(songHistory.size() - 2);
songHistory.remove(songHistory.size() - 1);
} else {
currentSong = songHistory.get(0);
}
previousSong = false;
} else {
currentSong = al1.get(new Random().nextInt(al1.size()));
songHistory.add(currentSong);
}
try {
fis = new FileInputStream(currentSong);
fd = fis.getFD();
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(fd);
mediaPlayer.prepare();
mediaPlayer.seekTo(songPosition);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.start();
playerStarted = true;
} catch (FileNotFoundException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#Override
public void onCompletion(MediaPlayer arg0) {
playNextSong();
}
}
I think I fixed it. The slider volume code was the source of the problem. Without that piece, the app was still working during standby mode using the bluetooth speakers. I wanted the slider bar, so I tried acquring a partial wake lock after instantiating the media player for each song and that kept the app going correctly duing standby mode (with the slider volume control as part of the app as well). I release the lock later after each song.
Related
I've this class (my media player class) and I need to create 2 methods on it, one to change the volume and other to get the current volume. (I'll create a seekbar to change the player volume), ok.
public class LoopMediaPlayer {
private Context ctx = null;
private int rawId = 0;
private MediaPlayer currentPlayer = null;
private MediaPlayer nextPlayer = null;
public static LoopMediaPlayer create(Context ctx, int rawId) {
return new LoopMediaPlayer(ctx, rawId);
}
private LoopMediaPlayer(Context ctx, int rawId) {
this.ctx = ctx;
this.rawId = rawId;
currentPlayer = MediaPlayer.create(this.ctx, this.rawId);
currentPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
currentPlayer.start();
}
});
createNextMediaPlayer();
}
private void createNextMediaPlayer() {
nextPlayer = MediaPlayer.create(ctx, rawId);
currentPlayer.setNextMediaPlayer(nextPlayer);
currentPlayer.setOnCompletionListener(onCompletionListener);
}
private MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.release();
currentPlayer = nextPlayer;
createNextMediaPlayer();
}
};
public void stopPlayer() {
if (currentPlayer != null && currentPlayer.isPlaying()) {
currentPlayer.stop();
currentPlayer.release();
}
if (nextPlayer != null && nextPlayer.isPlaying()) {
nextPlayer.stop();
nextPlayer.release();
}
}
public void setVolume(float vol) {
//todo
currentPlayer.setVolume(vol, vol);//don't work
}
public int getVolume(){
//todo
return 0;
}
}
and my seekBar progress and listener
seekBar.setProgress(player.getVolume());//use the method that retrieve the current volume
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, final int i, boolean b) {
runOnUiThread(new Runnable() {
#Override
public void run() {
player.setVolume(i);//use the method that change the volume
}
});
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
I tried mp.setVolume() but didn't change any thing. And I can't get the current volume to set like the seekbar progress before show it.
Details - All Audios are in raw file (not stream). There will be more than one player playing at same time, them will be stored so I can retrieve any of them any time, and I want to change and retrieve just the volume of a specific player not of all them at same time.
Anyone know how I should implement both this methods, 'cause I have no idea.
Thanks
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);
}
Please, I need my streaming audio player to be controlled from two different fragments:
Radiofragment and AboutFragment.
and here's my radio fragment
public class RadioFragment extends Fragment implements
MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener{
AudioManager am;
ImageButton btnPlay = null;
private boolean isPlaying;
private PlayerManager playerManager;
private View view;
public RadioFragment(boolean p, PlayerManager pmanager){
this.isPlaying = p;
this.playerManager = pmanager;
}
#Override
public View onCreateView(LayoutInflater l, ViewGroup container, Bundle onSavedInstance){
super.onCreateView(l, container, onSavedInstance);
view = l.inflate(R.layout.activity_radio, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
btnPlay = (ImageButton)view.findViewById(R.id.btnPlay);
addButtonListeners();
}
private void addButtonListeners()
{
btnPlay.setAlpha(155);
btnPlay.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
onClickBtnPlay(v);
}
});
}
protected void onClickBtnPlay(View v)
{
if (isPlaying){
playerManager.pause();
isPlaying = false;
}
else{
if (playerManager == null){
playerManager = new PlayerManager(getString(R.string.link_streaming_radio), RadioFragment.this);
}
playerManager.play();
isPlaying = true;
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra)
{
StringBuilder sb = new StringBuilder();
sb.append("Media Player Error: ");
switch (what)
{
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
}
sb.append(" (" + what + ") ");
sb.append(extra);
Log.e(MainActivity.TAG, sb.toString());
return true;
}
#Override
public void onPrepared(MediaPlayer mp)
{
mp.start();
}
#Override
public void onCompletion(MediaPlayer mp)
{
mp.stop();
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent)
{
Log.d(MainActivity.TAG, "PlayerService onBufferingUpdate : " + percent + "%");
}
}
in my AboutFragment, I have a layout with a play/pause button and
protected void onClickBtnPlay(View v)
{
if (isPlaying){
playerManager.pause();
isPlaying = false;
}
else{
if (playerManager == null){
playerManager = new PlayerManager(getString(R.string.link_streaming_radio), AboutFragment.this);
}
playerManager.play();
isPlaying = true;
}
}
here is the class where I controll the player:
public class PlayerManager{
private String xmlUrl;
private String server;
private MediaPlayer mp;
public PlayerManager(Fragment owner)
{
this.owner = owner;
this.server = "";
}
public void play()
{
server = path_to_server;
playMusic();
}
public void pause()
{
mp.stop();
mp.reset();
}
private void playMusic()
{
Uri myUri = Uri.parse(this.server);
try
{
if (mp == null){
this.mp = new MediaPlayer();
}
else{
mp.stop();
mp.reset();
}
mp.setDataSource(owner.getActivity(), myUri); // Go to Initialized state
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener((OnPreparedListener) this.owner);
mp.setOnBufferingUpdateListener((OnBufferingUpdateListener) this.owner);
mp.setOnErrorListener((OnErrorListener) this.owner);
mp.setVolume(100,100);
mp.prepareAsync();
Log.d(MainActivity.TAG, "Done");
}
catch (Throwable t)
{
Log.d(MainActivity.TAG, t.toString());
}
}
}
can it be done with this kind of implementation or I have to use another approach?
Because I tried to pass playerManager via constructor but it seems to be in other activity context
so i get class cast exceptions. I also tried to pass Radiofragment context and got some null pointer exceptions
both from this last catch block above.
I need some light here, please..
thank you in advance!
You should have a foreground Service, containing the PlayerManager. You will then send play/pause commands from any activity or fragment you want.
I am new to android. I am making a live audio streaming app(streams from a URL). As soon as I hit play, the audio plays but there is a stuttering about every half second. I checked the live audio URL on my computer and it plays perfectly. And I checked it in another audio streaming app I am making, using the same emulator, and it plays perfectly there too. The streaming file is .mp3. I have added the code.
public class StreamAudioFromUrlSampleActivity extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{
private Button btn_play,
btn_pause,
btn_stop;
//private SeekBar seekBar;
private MediaPlayer mediaPlayer;
private int lengt
hOfAudio;
private final String URL = "**some url**";
//private final Handler handler = new Handler();
/*private final Runnable r = new Runnable() {
#Override
public void run() {
//updateSeekProgress();
}
};*/
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();mediaPlayer = new MediaPlayer();
}
private void init() {
btn_play = (Button)findViewById(R.id.btn_play);
btn_play.setOnClickListener(this);
btn_pause = (Button)findViewById(R.id.btn_pause);
btn_pause.setOnClickListener(this);
btn_pause.setEnabled(false);
btn_stop = (Button)findViewById(R.id.btn_stop);
btn_stop.setOnClickListener(this);
btn_stop.setEnabled(false);
//seekBar = (SeekBar)findViewById(R.id.seekBar);
//seekBar.setOnTouchListener(this);
//mediaPlayer.setOnBufferingUpdateListener(this);
//mediaPlayer.setOnCompletionListener(this);
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
//seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mediaPlayer.isPlaying()) {
//SeekBar tmpSeekBar = (SeekBar)v;
//mediaPlayer.seekTo((lengthOfAudio / 100) * tmpSeekBar.getProgress() );
}
return false;
}
#Override
public void onClick(View view) {
try {
mediaPlayer.setDataSource(URL);
mediaPlayer.prepare();
//lengthOfAudio = mediaPlayer.getDuration();
} catch (Exception e) {
Log.e("Error", "error"+e);
}
switch (view.getId()) {
case R.id.btn_play:
playAudio();
break;
case R.id.btn_pause:
pauseAudio();
break;
case R.id.btn_stop:
stopAudio();
break;
default:
break;
}
//updateSeekProgress();
}
private void updateSeekProgress() {
if (mediaPlayer.isPlaying()) {
//seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / lengthOfAudio) * 100));
// handler.postDelayed(r, 1000);
}
}
private void stopAudio() {
mediaPlayer.stop();
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
mediaPlayer.release();
//seekBar.setProgress(0);
}
private void pauseAudio() {
mediaPlayer.pause();
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
}
private void playAudio() {try{
Thread.sleep(10000);}catch(InterruptedException x){}
mediaPlayer.start();
btn_play.setEnabled(false);
btn_pause.setEnabled(true);
btn_stop.setEnabled(true);
}
}
It is returning NullPointerException when I click play button where I want to bind the stop button with the value of getCount() method which is in the Service class which should return 1, it is crashing when I am clicking play button.
This is the activity class:
public class MainMP3 extends Activity{
Button stop;
static final String MEDIA_PATH = new String("/sdcard/");
Button data_display;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mp3interface);
startService(new Intent(MainMP3.this, ServiceMP3.class));
stop= (Button) findViewById(R.id.stop);
// to stop service
//stopService(new Intent(MainMP3.this, ServiceMP3.class));
Button button = (Button)findViewById(R.id.play);
button.setOnClickListener(new StartClick());
}
private ServiceMP3 service = null;
private ServiceConnection connection = new ServiceConnection() {
#Override // Called when connection is made
public void onServiceConnected(ComponentName cName, IBinder binder) {
service = ((ServiceMP3.SlowBinder)binder).getService();
}
#Override //
public void onServiceDisconnected(ComponentName cName) {
service = null;
}
};
private class StartClick implements View.OnClickListener {
public void onClick(View v) {
int data = service.getCount();
stop.setText(Integer.toString(data));
}
}
}
and here is Service:
public class ServiceMP3 extends Service {
private static final String MEDIA_PATH = new String("/sdcard/");
private MediaPlayer mp = new MediaPlayer();
private List<String> songs = new ArrayList<String>();
private int currentPosition;
int count=1;
private NotificationManager nm;
private static final int NOTIFY_ID = R.layout.song;
public int getCount() {return count;}
#Override
public void onCreate() {
super.onCreate();
BindAllSongs();
System.out.println(MEDIA_PATH+ songs.get(currentPosition));
for (int i = 0; i < songs.size(); i++) {
System.out.println(songs.get(i).toString());
}
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// playSong(MEDIA_PATH+ songs.get(currentPosition));
// Thread thr = new Thread(null, work, "Play Song");
// thr.start();
// Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
// player = MediaPlayer.create(ServiceMP3.this, R.raw.test);
// player.start();
// player.setLooping(true);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service started...", Toast.LENGTH_LONG).show();
return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
mp.stop();
mp.release();
nm.cancel(NOTIFY_ID);
Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
}
public void BindAllSongs()
{
// TODO Auto-generated method stub
//To hold all the audio files from SDCARD
File fileListBeforeFiltering = new File(MEDIA_PATH);
//Filter all the MP# format songs to list out
//Checking for the MP3 Extension files existence
if (fileListBeforeFiltering.listFiles(new FilterFilesByMp3Extension()).length > 0)
{
//Loop thru all the files filtered and fill them in SongsList view that we have
//Defined above.
for (File file : fileListBeforeFiltering.listFiles(new FilterFilesByMp3Extension()))
{
//Adding all filtered songs to the list
songs.add(file.getName());
}
}
}
void playSong(String file) {
try {
mp.setDataSource(file);
mp.prepare();
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer arg0) {
nextSong();
}
});
} catch (IOException e) {
Log.e(getString(R.string.app_name), e.getMessage());
}
}
void nextSong() {
// Check if last song or not
if (++currentPosition >= songs.size()) {
currentPosition = 0;
nm.cancel(NOTIFY_ID);
} else {
playSong(MainMP3.MEDIA_PATH + songs.get(currentPosition));
}
}
void prevSong() {
if (mp.getCurrentPosition() < 3000 && currentPosition >= 1) {
playSong(MainMP3.MEDIA_PATH + songs.get(--currentPosition));
} else {
playSong(MainMP3.MEDIA_PATH + songs.get(currentPosition));
}
}
Runnable work = new Runnable() {
public void run() {
while (true) {
System.out.println("Runnable method....");
}
}
};
private final IBinder binder = new SlowBinder();
#Override
public IBinder onBind(Intent intent) {
return binder;
}
public class SlowBinder extends Binder {
ServiceMP3 getService() {
return ServiceMP3.this;
}
}
}
First try to replace
startService(new Intent(MainMP3.this, ServiceMP3.class));
on
bindService(new Intent(MainMP3.this, ServiceMP3.class));
Read please: Bound Services