I'm having a problem with my radio, the radio works and everything, but the thing is that when I pressed Pause the radio stops, but, when i click on PLAY again, the radio starts again, but like if it where a song. Conclusion (sorry for my bad explanation)
when i use OnPause() this happens
weird example===
if I start playing 1:00pm , and then I paused 1:01pm, then wait a couple minutes, and play again, the radio will continue playing like if it where 1:01pm, and it's 1:05pm (awkward example)
when i changed to OnStop()
it gave me MediaPlayer code error(-38,0)
enter code here :::::: b_play = findViewById(R.id.b_play);
b_play.setEnabled(false);
b_play.setText("Cargando...");
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
new PlayerTask().execute(stream);
b_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (started) {
started = false;
mediaPlayer.stop();
b_play.setText("Escuchar");
} else {
started = true;
mediaPlayer.start();
b_play.setText("Pausar");
}
}
#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);
mediaPlayer.start();
b_play.setEnabled(true);
b_play.setText("Escuchar");
}
}
#Override
protected void onPause() {
super.onStop();
if (started) {
mediaPlayer.stop();
}
}
#Override
protected void onResume() {
super.onResume();
if (started) {
mediaPlayer.start();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (prepared) {
mediaPlayer.release();
}
}
If u could help me out, i'll do apprecciate, I'm sorry about my english and weird explanation (?
remove onPause with onStop
#Override
protected void onStop() {
super.onStop();
if (started) {
mediaPlayer.stop();
}
}
#Override
protected void onResume() {
super.onResume();
if (started) {
mediaPlayer.start();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (prepared) {
mediaPlayer.release();
}
}
Related
Currently working on an app in Android Studio to play music from a live audio source. I got the play and pause button to work for certain url's such as this, which may only work either because it's http. However, when doing it with this link, which is live audio from a college radio station, it doesn't play anything (the static when the station is not on can't be heard in the app).
My code is below:
public class RadioSelection extends AppCompatActivity {
ImageView fm;
ImageView digital;
MediaPlayer mediaPlayer;
ImageView playPause;
String stream = "http://wmuc.umd.edu:8000/wmuc-hq";
boolean prepared = false;
boolean started = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio_selection);
mediaPlayer=new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
new PlayerTask().execute(stream);
playPause = findViewById(R.id.play_pause);
fm = findViewById(R.id.fm);
digital = findViewById(R.id.digital);
playPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (started) {
started = false;
mediaPlayer.pause();
Toast.makeText(RadioSelection.this, "Paused", Toast.LENGTH_SHORT).show();
} else {
started = true;
mediaPlayer.start();
Toast.makeText(RadioSelection.this, "Playing", Toast.LENGTH_SHORT).show();
}
}
});
fm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
digital.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private class PlayerTask 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();
}
System.out.println("It's prepared!");
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
}
#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();
if (prepared) {
mediaPlayer.release();
}
}
}
I feel like it has to do with the protocol but I'm not sure, and I don't really know of a way to test if it actually successfully connected to the audio source. I'd really appreciate any help.
How to play android radio with screen off background playable option. My App working fine without backgournd playing option. But I want to give background playing option in my app that is when user closes the app, the radio should keep on playing, untill user stops it.
I am also disable screen off option in xml file with android:keepScreenOn="true" option but I want to remove this option and keep mobile screen off and play my app in background.
This is my code
Button BPlay;
String stream = "http://stream.zeno.fm/hmzuvfwn9k0uv";
MediaPlayer mediaPlayer;
boolean prepared = false;
boolean started = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
BPlay = (Button) findViewById(R.id.b_play);
BPlay.setEnabled(false);
BPlay.setText("Loading.....");
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
new PlayerTask().execute(stream);
BPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (started){
started = false;
mediaPlayer.pause();
BPlay.setText("PLAY");
} else {
started = true;
mediaPlayer.start();
BPlay.setText("PAUSE");
}
}
});
}
class PlayerTask 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);
BPlay.setEnabled(true);
BPlay.setText("PLAY");
}
}
#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();
if (prepared){
mediaPlayer.release();
}
}
}
In order to have you media playing while the app is in the background, you'll need a MediaSession background Service running in parallel.
TLTR, here's a basic tutorial from Google on how to do that.
in my app i want to offer the user a option to set an animation as live wallpaper using WallpaeprService, also my app include a Radio player (playing in the backgroud) if app is open so you can navigate in other apps while music is playing.
my problem :
if live wallpaper is working and user try to close the app by (Swipe to exit / Recent Task),the music keeps playing although app is closed.
i tried to stop music like this ,but doesn't work :
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
#SuppressLint({"CommitPrefEdits", "Assert"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, KillNotificationService.class));
trackSelector = new DefaultTrackSelector();
loadControl = new DefaultLoadControl();
exoPlayer = ExoPlayerFactory.newSimpleInstance(new DefaultRenderersFactory(getApplicationContext()), trackSelector, loadControl);
MusicButton.setVisibility(View.INVISIBLE);
MusicButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (Build.VERSION.SDK_INT > 15) {
if (started && MusicButton.isChecked()) {
started = false;
exoPlayer.setPlayWhenReady(false);
MusicButton.setChecked(true);
releaseAudioFocusForMyApp(MainActivity.this);
} else {
boolean gotFocus = requestAudioFocusForMyApp(MainActivity.this);
if (gotFocus) {
started = true;
exoPlayer.setPlayWhenReady(true);
MusicButton.setChecked(false);
}
}
} else {
if (started && MusicButton.isChecked()) {
started = false;
mediaPlayer.pause();
MusicButton.setChecked(true);
releaseAudioFocusForMyApp(MainActivity.this);
} else {
boolean gotFocus = requestAudioFocusForMyApp(MainActivity.this);
if (gotFocus) {
started = true;
mediaPlayer.start();
MusicButton.setChecked(false);
}
}
}
}
});
private void playRadio(String url) {
Uri audioUri = Uri.parse(url);
DefaultHttpDataSourceFactory dataSourceFactory = new DefaultHttpDataSourceFactory("ExoPlayerDemo");
ExtractorsFactory extractor = new DefaultExtractorsFactory();
MediaSource audioSource = new ExtractorMediaSource.Factory(dataSourceFactory).setExtractorsFactory(extractor).createMediaSource(audioUri);
exoPlayer.prepare(audioSource);
prepared = true;
exoPlayer.setPlayWhenReady(true);
exoPlayer.addListener(new Player.EventListener() {
#Override
public void onTimelineChanged(Timeline timeline, #Nullable Object manifest, int reason) {
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
#Override
public void onLoadingChanged(boolean isLoading) {
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (isPreparing && playbackState == ExoPlayer.STATE_READY) {
MusicButton.setVisibility(View.VISIBLE);
MusicButton.setChecked(true);
isPreparing = false;
isReady = true;
}
}
#Override
public void onRepeatModeChanged(int repeatMode) {
}
#Override
public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
}
#Override
public void onPlayerError(ExoPlaybackException error) {
}
#Override
public void onPositionDiscontinuity(int reason) {
}
#Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
#Override
public void onSeekProcessed() {
}
});
}
#Override
protected void onResume() {
super.onResume();
try {
MApplication.sBus.register(this);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
MApplication.sBus.unregister(this);
} catch (Exception e) {
e.printStackTrace();
}
MApplication.sBus.post(PlaybackEvent.PAUSE);
}
#Override
protected void onStart() {
super.onStart();
}
#Subscribe
public void handlePlaybackEvent(PlaybackEvent event) {
switch (event) {
case PAUSE:
if (Build.VERSION.SDK_INT > 15) {
if (exoPlayer.getPlayWhenReady()) {
exoPlayer.setPlayWhenReady(false);
MusicButton.setChecked(true);
}
} else {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
MusicButton.setChecked(true);
}
}
break;
case PLAY:
if (Build.VERSION.SDK_INT > 15) {
if (!exoPlayer.getPlayWhenReady()) {
exoPlayer.setPlayWhenReady(true);
MusicButton.setChecked(false);
}
} else {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
MusicButton.setChecked(false);
}
}
break;
}
}
#Override
public void onPause() {
super.onPause();
}
}
}
problem solved by checking if live wallpaper are running in the backgroud or not:
#Override
protected void onDestroy() {
super.onDestroy();
try {
WallpaperManager wpm = WallpaperManager.getInstance(this);
WallpaperInfo info = wpm.getWallpaperInfo();
if (info != null && info.getPackageName().equals(this.getPackageName())) {
/*stop music*/
} else {
Log.d(TAG, "We're not running");
}
} catch (Exception e) {
e.printStackTrace();
}
}
Please teach me how can I solve a MediaPlayer error. I have Mediaplayer, MediaController and listview. When I touch the list, a song starts with MediaController, but when I touch keycode_home and restart my app, the error occurs. Here is my code and error.
java.lang.RuntimeException: Unable to resume activity {}:
java.lang.IllegalStateException
Caused by: java.lang.IllegalStateException at android.media.MediaPlayer.getCurrentPosition(Native Method)
int si[]={R.raw.sample1,R.raw.sample2,R.raw.sample3};
onCreate
ItemBean IB1 = new ItemBean();
IB1.setName("sample1");
IB1.setUrl("http~");
ItemBean IB2 = new ItemBean();
IB2.setName("sample2");
IB2.setUrl("http~");
ItemBean IB3 = new ItemBean();
IB3.setName("sample3");
IB3.setUrl("http~");
List<ItemBean> list = new ArrayList<ItemBean>();
list.add(IB1);
list.add(IB2);
list.add(IB3);
mp = new MediaPlayer();
controller = new MediaController(this);
controller.setAnchorView(findViewById(R.id.mediaController));
controller.setMediaPlayer(this);
list2 = (ListView) findViewById(R.id.song_list);
SonglistAdapter_test adapter = new SonglistAdapter_test(getApplicationContext(),list);
list2.setAdapter(adapter);
list2.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
try {
mp.reset();
mp.release();
mp = MediaPlayer.create(SongsActivity.this,si[position]);
} catch (Exception e) {}
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
handler.post(new Runnable() {
#Override
public void run() {
controller.setEnabled(true);
controller.show(mp.getDuration());
mp.start();
try {
Method m = android.widget.MediaController.class.getDeclaredMethod("updatePausePlay");
m.setAccessible(true);
m.invoke(controller);
} catch (Exception e) {
}
}
});
}
});
}
#Override
public void start(){
mp.start(); }
#Override
public void pause(){
mp.pause(); }
#Override
public int getDuration(){
return mp.getDuration(); }
#Override
public int getCurrentPosition(){
return mp.getCurrentPosition(); }
#Override
public void seekTo(int pos){
mp.seekTo(pos); }
#Override
public boolean isPlaying(){
return mp.isPlaying(); }
#Override
public int getBufferPercentage(){
return 0; }
#Override
public boolean canPause(){
return true; }
#Override
public boolean canSeekBackward(){
return true; }
#Override
public boolean canSeekForward(){
return true; }
#Override
public int getAudioSessionId(){
return 0; }
#Override
protected void onPause(){
super.onPause();
}
#Override
protected void onResume(){
super.onResume();
}
#Override
protected void onStop(){
super.onStop();
controller.hide();
mp.stop();
mp.release();
}
#Override
public void onRestart(){
super.onRestart();
controller.show();
}
#Override
protected void onDestroy(){
super.onDestroy();
finish();
}
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
finish();
}
return super.dispatchKeyEvent(event);
}
The problem is in your onStop() method -- you are releasing your media player there and not recreating it before you show the controller during onRestart(). The onStop() method is not the same as onDestroy() -- onStop() doesn't mean that your activity will necessarily run through onCreate() again when it is resumed.
You should have a look at the Activity Lifecycle to get a better understanding of when these events occur.
I seem to be having the same problem as this gentleman:
SensorEventListener doesn't get unregistered with unregisterListener() method
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
...
loopThread();
}
private void loopThread() {
boolean found = kill;
System.out.println("Looping until Found!");
locationThread = new Thread(){
private float myacc;
#Override
#Override
public void run() {
while (found == false && !kill){
System.out.println("Another Loop!");
getMyLoc();
found = isFound(mylat,mylng,target_lat,target_lng,radius);
try {
synchronized(locationThread){
locationThread.wait(100);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mSensorManager.unregisterListener(senslistener, mAccelerometer);
mSensorManager.unregisterListener(senslistener, mGravitometer);
mSensorManager.unregisterListener(senslistener);
locationThread.interrupt();
}
}
#Override
public void onPause(){
super.onPause();
mSensorManager.unregisterListener(senslistener, mAccelerometer);
mSensorManager.unregisterListener(senslistener, mGravitometer);
locationThread.interrupt();
}
#Override
public void onResume(){
super.onResume();
senslistener = new mySensorEventListener();
mSensorManager.registerListener(senslistener, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(senslistener, mGravitometer, SensorManager.SENSOR_DELAY_NORMAL);
if (true)
loopThread();
}
private void registerSensors() {
mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
List<Sensor> mySensors = mSensorManager.getSensorList(Sensor.TYPE_ORIENTATION);
if(mySensors.size() > 0){
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mGravitometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mSensorManager.registerListener(senslistener, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(senslistener, mGravitometer, SensorManager.SENSOR_DELAY_NORMAL);
Toast.makeText(context, "Getting your location...", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(context, "No ORIENTATION Sensor", Toast.LENGTH_LONG).show();
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent i = new Intent(this, MFLMain.class);
if (locationThread != null)
if(locationThread.isAlive()){
mSensorManager.unregisterListener(senslistener, mAccelerometer);
mSensorManager.unregisterListener(senslistener, mGravitometer);
mSensorManager.unregisterListener(senslistener);
locationThread.interrupt();
}
locator.stopListener();
kill = true;
System.out.println("Kill the app "+kill);
finish();
startActivity(i);
return false;
}
return super.onKeyDown(keyCode, event);
}
When I hit back to hide the application and kill the activity, I still get the system.out in logcat. The thead quits, as evidenced by the lack of system.out there. I am very confused and I don't think scope is the issue as the sensormanager is being instantiated through an init method and nowhere else .
maybe a long shot but the only thing I can see different from examples that have worked and yours ( without seeing additional code ) would be to implement the SensorEventListener and pass this into the register and unregister events instead of your custom SensorEventListener.
see this stackoverflow of someone trying it your way by using the new operator to instantiate the listener and the answer that seemed to work for him.
How to convert a program that uses SensorListener to SensorEventListener
public class MySensorActivity extends Activity implements SensorEventListener {
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
...
loopThread();
}
private void loopThread() {
boolean found = kill;
System.out.println("Looping until Found!");
locationThread = new Thread(){
private float myacc;
#Override
#Override
public void run() {
while (found == false && !kill){
System.out.println("Another Loop!");
getMyLoc();
found = isFound(mylat,mylng,target_lat,target_lng,radius);
try {
synchronized(locationThread){
locationThread.wait(100);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mSensorManager.unregisterListener(this, mAccelerometer);
mSensorManager.unregisterListener(this, mGravitometer);
mSensorManager.unregisterListener(this);
locationThread.interrupt();
}
}
#Override
public void onPause(){
super.onPause();
mSensorManager.unregisterListener(this, mAccelerometer);
mSensorManager.unregisterListener(this, mGravitometer);
locationThread.interrupt();
}
#Override
public void onResume(){
super.onResume();
registerSensors();
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mGravitometer, SensorManager.SENSOR_DELAY_NORMAL);
if (true)
loopThread();
}
private void registerSensors() {
mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
List<Sensor> mySensors = mSensorManager.getSensorList(Sensor.TYPE_ORIENTATION);
if(mySensors.size() > 0){
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mGravitometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mGravitometer, SensorManager.SENSOR_DELAY_NORMAL);
Toast.makeText(context, "Getting your location...", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(context, "No ORIENTATION Sensor", Toast.LENGTH_LONG).show();
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent i = new Intent(this, MFLMain.class);
if (locationThread != null)
if(locationThread.isAlive()){
mSensorManager.unregisterListener(this, mAccelerometer);
mSensorManager.unregisterListener(this, mGravitometer);
mSensorManager.unregisterListener(this);
locationThread.interrupt();
}
locator.stopListener();
kill = true;
System.out.println("Kill the app "+kill);
finish();
startActivity(i);
return false;
}
return super.onKeyDown(keyCode, event);
}