How can I play sound on all of my activities - java

I want to use my sound on all my activities not only main activity. I put this lines
MediaPlayer ring = MediaPlayer.create(MainActivity.this, R.raw.song);
ring.start();
but that works only in main Activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaPlayer ring = MediaPlayer.create(MainActivity.this, R.raw.song);
ring.start();

you can try something like this
1. add this code in your all activity
MediaPlayer ring = MediaPlayer.create(MainActivity.this,
R.raw.song);
ring.start();
2. create one method like this and call this msg from your activity in which you want to play music
public void Playmusic(Context context){
MediaPlayer ring = MediaPlayer.create(context, R.raw.song);
ring.start();
}
now just call this method like this
Playmusic(MainActivity.this);

play your songs in service and initialize the media player object there only
Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.idil);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
Please call this service in Manifest
<service android:enabled="true" android:name=".BackgroundSoundService " />

Related

How to play music on Android while activities are on foreground

I want to play music in the background of my application:
public class BackgroundSoundService extends Service {
MediaPlayer mediaPlayer;
#Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(this, R.raw.airport_lounge);
mediaPlayer.setLooping(true);
mediaPlayer.setVolume(100,100);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mediaPlayer.start();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
mediaPlayer.release();
}
#Override
public void onLowMemory() {
super.onLowMemory();
}
#Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Then in my MainActivity :
public static Intent musicIntent;
//Start music service
musicIntent = new Intent(this, BackgroundSoundService.class);
startService(musicIntent);
#Override
protected void onPause() {
super.onPause();
stopService(musicIntent);
}
#Override
protected void onResume() {
super.onResume();
startService(musicIntent);
}
I stop it in my onPause the service because if the user switches the Application and doesn't close it the music would continue to play. The problem is that when we change Activity the onPaused is also called but I want the music to continue playing through the entire application.
So in my another Activity :
//start music
startService(MainActivity.musicIntent);
But the music restarts and it's not very good to hear. Any solutions?
You can use ActivityLifecycleCallbacks in your application class.
public class MusicApplication extends Application implements ActivityLifecycleCallbacks {
int activitiesOnTop = 0;
#Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(this);
}
#Override
public void onActivityResumed(Activity activity) {
// one of application activities is visible
activitiesOnTop ++;
}
#Override
public void onActivityStopped(Activity activity) {
activitiesOnTop --;
if(activitiesOnTop == 0){
// none of activities are on foreground
}
}
}
There are other solutions mentioned in the How to check if activity is in foreground or in visible background?.
It depends on the application structure, for example, if you build some tab or navigationDrawer based navigation, you will likely build some fragments and your MainActivity will be your only activity, so it's onPause method will only be called if user closes your application. But this scenario won't hold as your application grows (unless it's quite simple).
So another approach is to launch your service in your application instance, in case you use it.

How can i run a background(for O and above) music in android studio even if app is closed?

I want to play my ringtone in my android app in background(for version O and above) even if application is closed and stop playing if i stop from my app.
I used service in my application but the music is stopped when i closed my app.
How can i achieve this ??
Here is my Service class:
public class MyService extends Service {
MediaPlayer player;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
player=MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
player.setLooping(true);
player.setVolume(100,100);
player.start();
player.start();
return START_STICKY;
}
#Override
public void onDestroy() {
player.stop();
player.release();
super.onDestroy();
}
}
and here is my MainActivity class from where I'm starting and stopping the service:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void Start(View view) {
startService(new Intent(this,MyService.class));
}
public void Stop(View v){
stopService(new Intent(this,MyService.class));
}
public void go(View view) {
startActivity(new Intent(MainActivity.this,NotActivity.class ));
}
}
From the code that you submitted, you have never invoked the service of the player. call the functions that you have created in oncreate method that should do the trick.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//button objects
private Button buttonStart;
private Button buttonStop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//getting buttons from xml
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);
//attaching onclicklistener to buttons
buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view == buttonStart) {
//starting service
startService(new Intent(this, MyService.class));
} else if (view == buttonStop) {
//stopping service
stopService(new Intent(this, MyService.class));
}
}
}
note: Create two buttons to start and stop the service
For more info check out: https://www.simplifiedcoding.net/android-service-example/

Music stops on moving to another activity, while using background service to play music

I'm developing a game, I have used services to play music on all activities.
I want to stop the music when we hit the home key, it shouldn't stop playing music when moving from one activity to another.
public class backService extends Service {
private MediaPlayer mp;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
mp.stop();
mp.release();
}
#Override
public void onCreate() {
super.onCreate();
mp = MediaPlayer.create(this, R.raw.all);
mp.setLooping(true);
mp.start();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
and my main activity file
public class Home extends AppCompatActivity {
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
hide();
setContentView(R.layout.activity_home);
Intent i = new Intent(this, backService.class);
adv();
}
#Override
protected void onResume(){
super.onResume();
Intent i = new Intent(this, backService.class);
startService(i);
}
#Override
protected void onStop() {
super.onStop();
Intent i = new Intent(this, backService.class);
stopService(i);
}
#Override
protected void onDestroy(){
super.onDestroy();
Intent i = new Intent(this, backService.class);
stopService(i);
}
}
How can I stop the music when I hit the home key and keep playing the music when we switch between other activities
TIA
Please remove the stopService(i) inside onStop() method in Activity coz whenever you are going one Activity to Another Activity then onStop() method will be called, that's why your service is killing.
If you want to pause or stop music while press home button then implements ComponentCallbacks2 interface to Activity like this
#Override
public void onTrimMemory(final int level) {
if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
if(mService != null){
mService.pauseMusic();
}
}
}
Try to stop the service in
#Override
public void onPause()
{
super.onPause();
// Check if app is in foreground
if(!isAppOnForeground(context))
{
stop music here
}
}
below is the method to check if the app is in foreground or not . just replace your package here "your package name here";
public static boolean isAppOnForeground(Context context)
{
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null) {
return false;
}
final String packageName = "your package name here";
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
return true;
}
}
return false;
}

saving activity state in media Player

I am an absolute beginner working on my first android app. I am working on an audio stream app and i implemented the mediaPlayer inside a service. There is a play-pause button that toggles if bound or not. The issue i have is that when isPlaying, and i change the screen orientation, though the service continues, the activity is recreated which makes the play button appear rather than the pause button. I know for me to retain the pause button, i need to override two methods - onSaveInstanceState and onRestoreInstanceState but i dont know the right logic to use in order to retain mainActivity's state.
Pls help me because the examples i saw didnt solve my problem.
This is my main activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//.......
if(savedInstanceState != null) {
boolean isPlaying = savedInstanceState.getBoolean("isPlaying");
if(!isPlaying){
imageButton2.setImageResource(R.drawable.stop);
} else {
imageButton2.setImageResource(R.drawable.play);
}
}
#Override
protected void onStart() {
// bind to the radio service
Intent intent = new Intent(this, RadioService.class);
startService(intent);
bindService(intent, mConnection, BIND_AUTO_CREATE);
super.onStart();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onStop() {
// unbind the radio
// service
if (boundToRadioService) {
unbindService(mConnection);
boundToRadioService = false;
}
super.onStop();
}
#Override
protected void onDestroy() {
radioService.hideNotification();
if (boundToRadioService) {
unbindService(mConnection);
boundToRadioService = false;
}
super.onDestroy();
}
public void setupMediaPlayer(View view) {
if (boundToRadioService) {
boundToRadioService = false;
imageButton2.setImageResource(R.drawable.stop);
radioService.play();
} else {
boundToRadioService = true;
imageButton2.setImageResource(R.drawable.play);
radioService.pause();
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("isPlaying", boundToRadioService);
super.onSaveInstanceState(outState);
}
}
This is my Service
// Binder given to clients
private final IBinder mBinder = new RadioBinder();
}
public void pause() {
audioManager.abandonAudioFocus(audioFocusChangeListener);
unregisterReceiver(audioBecomingNoisy);
mediaPlayer.pause();
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(this, "Oops! Error Occured, Check your network connection", Toast.LENGTH_SHORT).show();
mediaPlayer.reset();
return false;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
#Override
public void onPrepared(MediaPlayer mp) {
{
mp.start();
}
}
public class RadioBinder extends Binder {
RadioService getService() {
// Return this instance of RadioBinder so clients can call public methods
return RadioService.this;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind: ");
return mBinder;
}
public void play() {
registerReceiver(audioBecomingNoisy, noisyIntentFilter);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
new PlayerTask().execute(stream);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.reset();
showNotification();
Toast.makeText(this, "loading... please wait", Toast.LENGTH_LONG).show();
Log.i(TAG, "onCreate, Thread name " + Thread.currentThread().getName());
}
class PlayerTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.setDataSource(stream);
mediaPlayer.prepareAsync();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
}
return prepared;
}
}
try this,
public class MainActivity extends AppCompatActivity {
private boolean boundToRadioService = false;
private ImageButton imageButton2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageButton2 = (ImageButton) findViewById(R.id.my_button);
if(savedInstanceState != null){
boundToRadioService = savedInstanceState.getBoolean("isPlaying", false);
if(boundToRadioService){
imageButton2.setImageResource(R.drawable.stop);
} else {
imageButton2.setImageResource(R.drawable.play);
}
} else {
// bind to the radio service
Intent intent = new Intent(this, RadioService.class);
startService(intent);
bindService(intent, mConnection, BIND_AUTO_CREATE);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putBoolean("isPlaying", boundToRadioService);
super.onSaveInstanceState(outState);
}
public void setupMediaPlayer(View view){
if (boundToRadioService) {
boundToRadioService = false;
imageButton2.setImageResource(R.drawable.play);
radioService.pause();
} else {
boundToRadioService = true;
imageButton2.setImageResource(R.drawable.stop);
radioService.play();
}
}
}
and add android:src="#drawable/play" to the imagebutton in your xml file.

Not able to function the media player properly in the background services

I have implemented the media player in my project and I want to play the music even when I close my application , but when I kill my application then it should stop playing the music.
My problem which I am facing is that my application starts playing the music again with the previous one playing already whenever I open my unkilled application again.What am i doing wrong ??
My requirement is that the music should start playing as soon as i open the app,and it should keep on playing in the background even if i close(not killed) my app.But when i kill my app then the music should stop playing
Here is my code -
Main_activity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
String msg = "Android : ";
private Button play,pause,restart;
LocalService mService;
boolean mBound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play=(Button) findViewById(R.id.play);
pause=(Button) findViewById(R.id.pause);
restart=(Button) findViewById(R.id.restart);
play.setOnClickListener(this);
pause.setOnClickListener(this);
restart.setOnClickListener(this);
Intent intent = new Intent(this, LocalService.class);
startService(intent);
}
/** Called when the activity is about to become visible. */
#Override
protected void onStart() {
super.onStart();
Log.d(msg, "The onStart() event");
Intent intent = new Intent(this, LocalService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
/** Called when the activity has become visible. */
#Override
protected void onResume() {
super.onResume();
Log.d(msg, "The onResume() event");
}
/** Called when another activity is taking focus. */
#Override
protected void onPause() {
super.onPause();
Log.d(msg, "The onPause() event");
}
/** Called when the activity is no longer visible. */
#Override
protected void onStop() {
super.onStop();
Log.d(msg, "The onStop() event");
}
/** Called just before the activity is destroyed. */
#Override
public void onDestroy() {
super.onDestroy();
Log.d(msg, "The onDestroy() event");
Log.d("mbound value",mBound+"");
if (mBound) {
Intent intent=new Intent(this,LocalService.class);
stopService(intent);
unbindService(mConnection);
mBound = false;
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case(R.id.play):
if(mBound)
mService.start_mp();
break;
case(R.id.pause):
if(mBound)
mService.pause_mp();
break;
case (R.id.restart):
if(mBound)
mService.restart_mp();
break;
default:
break;
}
}
/** Defines callbacks for service binding, passed to bindService() */
public ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
LocalService.LocalBinder binder = (LocalService.LocalBinder) service;
mService = binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
}
LocalService.java
public class LocalService extends Service {
private MediaPlayer mediaPlayer;
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.i("Onbind called","");
return mBinder;
}
/** Called when the service is being created. */
#Override
public void onCreate() {
super.onCreate();
mediaPlayer=MediaPlayer.create(this,R.raw.jingle);
}
/** The service is starting, due to a call to startService() */
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mediaPlayer.start();
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
/** Called when all clients have unbound with unbindService() */
#Override
public boolean onUnbind(Intent intent) {
return true;
}
/** Called when a client is binding to the service with bindService()*/
#Override
public void onRebind(Intent intent) {
super.onRebind(intent);
}
/** Called when The service is no longer used and is being destroyed */
#Override
public void onDestroy() {
super.onDestroy();
// Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
LocalService getService() {
// Return this instance of LocalService so clients can call public methods
return LocalService.this;
}
}
public void start_mp(){
if(!mediaPlayer.isPlaying())
mediaPlayer.start();
}
public void pause_mp(){
mediaPlayer.pause();
}
public void restart_mp(){
if(mediaPlayer.isPlaying()) mediaPlayer.release();
mediaPlayer=MediaPlayer.create(this,R.raw.jingle);
mediaPlayer.start();
}
}
P.S.-I have applied the buttons in my application for the player functionality inside my app .
I got the solution.Whenever I press my homebutton ,then my onstop() method is executed and I get whatever I aim at,on pressing back button the default action of android is to destroy the activity.
Pressing the default back button of android device will call the finish() method of the activity and hence OnDestroy() will be called,by pressing the HomeButton the OnStop() method will be called.

Categories