I am using a mediaplayer service to stream mp3 from url. After read all documentation and dozens of posts, following is my last code. This code works properly on all emulators but only works on some devices and, strange behaviour, some of them with same OS (kit kat for example), works in some and others not... Errors were debugged and, looking at logcat, seems that does prepareAsync() properly but never throws onPrepared(). After publishing the app, test devices that were running while debbuging, doesn't stream music too!
public class backgroundAudio extends Service implements MediaPlayer.OnPreparedListener {
MediaPlayer mediaPlayer;
WifiLock wifiLock;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
mediaPlayer = null;
String url = "http://www.myserver.com/mystream.mp3";
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE)).createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");
wifiLock.acquire();
try {
mediaPlayer.setDataSource(url);
mediaPlayer.prepareAsync();
// it takes so long, about a minute...
} catch (IllegalArgumentException | SecurityException
| IllegalStateException | IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
/** Called when MediaPlayer is ready */
public void onPrepared(MediaPlayer player) {
mediaPlayer.start();
radio0.tabBridge.setStopView();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
wifiLock.release();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
stopSelf();
}
related manifest permissions,
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
There is no @Override
annotation on the onPrepared()
method. Normally it shouldn't be a problem, but who knows.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With