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.
Related
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.
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/
I have a Service (Bound) which I am trying to start from my MainActivity.java. The below is my Main Activity code:
public class MainActivity extends AppCompatActivity {
Handler m_handler;
Runnable m_handlerTask ;
private static ServiceConnection sConnection;
static boolean serviceBound = false;
#Override
protected void onStart() {
super.onStart();
// Bind to LocalService
Intent intent = new Intent(this, DataDownloaderService.class);
bindService(intent, sConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.NoActionBar);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
if (!Global.isMyServiceRunning(DataDownloaderService.class, this)) {
sConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
DataDownloaderService.LocalBinder binder = (DataDownloaderService.LocalBinder) service;
Global.dService = binder.getService();
serviceBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
serviceBound = false;
}
};
}
}
catch(Exception ex ){
String p="";
}
}
#Override
protected void onResume(){
super.onResume();
m_handler = new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
RefreshNowPlaying();
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();
}
}
void RefreshNowPlaying(){
//Do something
}
}
The service code is as shown below:
public class DataDownloaderService extends Service {
private final IBinder dBinder = new LocalBinder();
public class LocalBinder extends Binder {
DataDownloaderService getService() {
// Return this instance of LocalService so clients can call public methods
return DataDownloaderService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return dBinder;
}
#Override
public void onCreate(){
}
#Override
public void onStart(Intent intent, int startid){
super.onStart(intent,startid);
Global.DataDownloaderServiceStatus = "STARTED";
}
#Override
public void onDestroy(){
Global.DataDownloaderServiceStatus = "STOPPED";
super.onDestroy();
}
}
I have also added the service to the AndroidManifest.xml under the Application element. However, I see that the service's onStart is never fired or the override onServiceConnected in the MainActivity is never called. I am new to Anrdoid development and Java. Can someone give me some pointers, please? I have noticed that the service's onCreate is getting hit, by putting breakpoints, but not onStart.
onStart() will be called only if the service was started via context.startService(), see here.
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;
}
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 " />