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.
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.
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();
}
}
I built app to play audio from internet, I use service to play audio in background, the question is how to show loding dialog while media player is in preparing posision in service(background) hire my Code.
Activity
package com.uqifm.onlineradio;
.......
public class MainActivity extends AppCompatActivity {
Button b_play;
Boolean started = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b_play = (Button) findViewById(R.id.b_play);
b_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(started){
started = false;
stopService(new Intent(MainActivity.this,MyService.class));
b_play.setText("PLAY");
}else{
started = true;
startService(new Intent(MainActivity.this,MyService.class));
b_play.setText("STOP");
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
stopService(new Intent(MainActivity.this,MyService.class));
}
}
Service
package com.uqifm.onlineradio;
....................
public class MyService extends Service {
MediaPlayer mediaPlayer;
String stream = "http://xxxxx:36365";
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(stream);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mediaPlayer.start();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
mediaPlayer.release();
}
}
Register broadcasts, Start a ProgressDialog before you start the service. Then wait for the broadcast. After the broadcast, hide the dialog. see example in this thread. Send data from Service back to my activity
Put a ProgressDialog in xml and set the visibility according to your requirement. Use interface for communicating with service.
You can use Broadcast or try EventBus which is much more easier. You can post an event from the service using EventBus and receive the the broadcast in MainActivity and update the progress dialogue.
Please follow the link.
Maybe something like this:
fun playAudio(audioUrl: String){
showProgressBar()
var mediaPlayer: MediaPlayer? = MediaPlayer().apply {
setAudioStreamType(AudioManager.STREAM_MUSIC)
setDataSource(audioUrl)
prepareAsync() // might take long! (for buffering, etc)
}
mediaPlayer?.setOnPreparedListener {
hideProgressBar()
it.start()
}
mediaPlayer?.setOnCompletionListener {
mediaPlayer.release()
}
}
I'm using a simple activity (from this library) with ZXing to scan a barcode.
Everything works fine, but the transition between the MainActivity and the ScannerActivity doesn't work well. Halfway through it gets interrupted. When going back from the ScannerActivity to the MainActivity the transition works like desired. Only while loading the barcodescanner it doesn't look really good.
Do you have any idea how to fix this?
MainActivity:
private void invokeScanner() {
try {
Intent intent = new Intent(this, ScannerActivity.class);
stealFocus(et_loadInput);
startActivityForResult(intent,0);
this.overridePendingTransition(R.anim.detail_anim_up, R.anim.detail_anim_down);
} catch (Exception e){
Log.e(TAG, "couldn't open scanner");
e.printStackTrace();
openAlertDialog(Const.MSG_PROCESSING_ERROR);
}
}
ScannerActivity:
public class ScannerActivity extends AbstractTitleBarActivity implements ZXingScannerView.ResultHandler{
private ZXingScannerView mScannerView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
this.tv_backTitle.setText(getString(R.string.TITLE_SEARCH_VIEW));
this.tv_heading.setText("");
TextView titleClose = (TextView) findViewById(R.id.btn_close);
titleClose.setVisibility(View.VISIBLE);
titleClose.setOnClickListener(titleCloseListener);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.startCamera(); // Start camera on resume
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera(); // Stop camera on pause
}
#Override
protected boolean isBackBtnVisible() {
return false;
}
#Override
protected boolean isLogoVisible() {
return false;
}
#Override
public void handleResult(Result rawResult) {
Log.v(TAG, rawResult.getText()); // Prints scan results
Log.v(TAG, rawResult.getBarcodeFormat().toString()); // Prints the scan format (qrcode, pdf417 etc.)
MainActivity.scanVal = rawResult.toString();
MainActivity.loadVal = MainActivity.scanVal;
finish();
overridePendingTransition(R.anim.detail_anim_back_down,R.anim.detail_anim_back_up);
}
// listener for close button
protected TextView.OnClickListener titleCloseListener = new TextView.OnClickListener() {
public void onClick(View v) {
finish();
overridePendingTransition(
R.anim.detail_anim_back_down, R.anim.detail_anim_back_up);
}
};
}
I actually solved my own problem :D with this answer.
I just put the ZXingScannerView into a fragment and added a surface view with 0px height as a sibling. Now the animation works fine and the barcode scanner loads without refreshing the complete activity.
I was having some problem for Android activity transition. Basically what I am trying to do is share text to Twitter. However, when I open up the twitter content, it took quite a few seconds to load up the content and resulting in the white blank activity for a few seconds.
And here is my codes, when my button onClick, I am executing the loading dialog:
ivTwitterShare.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Thread newThread = new Thread() {
#Override
public void run() {
try {
super.run();
sleep(10000);
} catch (Exception e) {
} finally {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri
.parse(tweetUrl));
startActivity(intent);
progressDialog.dismiss();
}
}
};
newThread.start();
new LoadTwitterTask().execute();
}
});
private class LoadTwitterTask extends AsyncTask<Void, Integer, Void> {
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(context, "Loading Twitter...",
"Retrieving Twitter information, please wait...", false,
false);
EventDialogueBox.customizeDialogueBox(context, progressDialog);
}
#Override
protected Void doInBackground(Void... params) {
try {
synchronized (this) {
int counter = 0;
while (counter <= 4) {
this.wait(50);
counter++;
publishProgress(counter * 25);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result) {
}
}
However, my problem now is the white blank page before the content is loaded up still there. What I wanted is firstly, the loading dialog will show. Then, at the same time, the twitter intent is loading. Once finish loaded up the content, then dialog will be dismissed.
Any ideas?
Thanks in advance.