I'm relatively new to android development and I'm trying to make a game in Android Studio where I want background music to play. Here is my code for the service:
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.backgroundmusic);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
player.pause();
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
player.pause();
}
}
And in the activity where I want to initialise the backgroundmusic
Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);
which is placed in the onCreateMethod. When I open the activity where I call the service to play the music, nothing happens, total silence.
For some further details: the backgroundmusic file is in a .mp3 format and the phone on which I do my testing is a Nexus 6 running the latest version of Marshmallow.
I'm probably missing something obvious, can anyone point it out for me and/or give any tips on how to do it better in the future? Thanks in advance.
try this piece of code for running the music on the start up
public class start extends Activity {
MediaPlayer intro;
#Override
protected void onCreate(Bundle Start) {
// TODO Auto-generated method stub
super.onCreate(Start);
setContentView(R.layout.start);
intro = MediaPlayer.create(start.this,R.raw.SONGNAME);
intro.start();
Thread timer = new Thread() {
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent openStart = new Intent("com.example.main.MAIN");
startActivity(openStart);
}
}
};
timer.start();
}
#Override
protected void onPause() {
super.onPause();
intro.release();
finish();
}
and make sure that the music file is located in the correct folder (raw)
Try to add a prepare-Listener:
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "preparation Completed ...playing ");
player.start();
}
});
I think the setVolume is by default handled with a float (0=off, 1=max). Check your log output too. Sometimes the MediaPlayer is reporting a error-code.
EDIT / Second approach:
Did you added this line to your manifest (inside application tag)?
<application
... >
<service android:name="BackgroundSoundService" android:enabled="true"></service>
Related
I have added services to play music in background but after few minutes it's stop playing. So I have added Thread to start again while user remove the lock screen. And again music continue playing. But how we can continue play music in background without user interaction.
Here is my code,
MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, MyService.class));
}
}
MyService:
public class MyService extends Service {
private MediaPlayer mediaPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mediaPlayer = new MediaPlayer();
String file_path = "https://...aac";
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(file_path);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mediaPlayer.prepareAsync();
mediaPlayer.setLooping(true);
} catch (IOException e) {
e.printStackTrace();
}
//Thread
new Thread(
new Runnable() {
#Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
).start();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
}
}
AndroidManifest:
Heres my problem:
I am implementing a music player (PlayerActivity.java / xml) which is bound to a service (PlayerService.java) that basically is just an instance of a musicplayer so that it can run in the background. When lefting the app or changing the activity and the restarting the activity i want to bind to the still running service without stopping or restarting it. I have tried using only bindService() but that made me face the problem: somehow without calling startService() before bindService the Service doesn't get initialized or it takes a few milliseconds so that the functions only get null when accessing service functions.
Here is my service class:
public class playerService extends Service {
public boolean running = false;
public MediaPlayer mediaPlayer;
public boolean isPrepared = false;
private String url;
public class serviceBinder extends Binder {
public playerService getService() {
return playerService.this;
}
}
public boolean isRunning(){
return running;
}
private IBinder mBinder = new serviceBinder();
#Nullable
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.w("Service", "started");
mediaPlayer = new MediaPlayer();
running = true;
Log.e("!!!", running + "");
return START_STICKY;
}
public void pause() {
mediaPlayer.pause();
}
public void resume() {
mediaPlayer.start();
}
public void setupPlayer() {
try {
if (mediaPlayer != null) {
mediaPlayer.reset();
}
} catch (Exception e) {
Log.e("MediaPlayer", e.getMessage());
}
try {
mediaPlayer.setDataSource(url);
mediaPlayer.prepareAsync();
} catch (Exception e) {
Log.e("MediaPlayerToo", e.getMessage());
}
}
public void reset(){
mediaPlayer.reset();
}
public void updateUrl(String url){
this.url = url;
}
public void start(){
mediaPlayer.start();
}
public int getCurrentPosition(){
return mediaPlayer.getCurrentPosition();
}
public int getDuration(){
return mediaPlayer.getDuration();
}
#Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
mediaPlayer.reset();
}
}
I experimented with waiting until the Service has started with a boolean. But when i add any kind of code
after
mService = binder.getService();
startService(intent);
it seems to not get created at all.
Here is also my onServiceConnected class
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
playerService.serviceBinder binder = (playerService.serviceBinder) service;
Intent intent = new Intent(getApplicationContext(), playerService.class);
mService = binder.getService();
startService(intent);
//... <- adding code here will result in the Service not starting?!!
}
I know that my problem is quite confusing, but this was the best i could come up explaining it. I would be really glad if you had any idea because this problem stops me from deployment. Thank you very much!!
I'm developing music player app that runs music on the background service and when I leave the app media player stops.
This is my code when I leave the app media player mustn't be playing.
class MusicService extends Service{
private MediaPlayer mediaPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
private void initPlayer(){
if (mediaPlayer==null){
mediaPlayer =new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(this,Settings.System.DEFAULT_RINGTONE_URI);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent!=null && intent.getAction()!=null && intent.getAction().equals("com.play")){
mediaPlayer.start();
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
If you mean to keep playing the music in the background after leaving the app, update the manifest too:
Android background music service
as this post describes.
I'm developing a simple Android game that plays sound in background by service. When game starts, the sound is playing good. But when pressing volume up key or down button, the app exits immediately.
public class PlayAudio extends Service{
private static final String LOGCAT = null;
MediaPlayer objPlayer;
public void onCreate(){
super.onCreate();
Log.d(LOGCAT, "Service Started!");
objPlayer = MediaPlayer.create(this,R.raw.relax);
}
public int onStartCommand(Intent intent, int flags, int startId){
objPlayer.start();
Log.d(LOGCAT, "Media Player started!");
if(objPlayer.isLooping() != true){
Log.d(LOGCAT, "Problem in Playing Audio");
}
return 1;
}
public void onStop(){
objPlayer.stop();
objPlayer.release();
}
public void onPause(){
objPlayer.stop();
objPlayer.release();
}
public void onDestroy(){
objPlayer.stop();
objPlayer.release();
}
#Override
public IBinder onBind(Intent objIndent) {
return null;
}
}
this code to start playing sound
public void playAudio() {
Intent objIntent = new Intent(this, PlayAudio.class);
startService(objIntent);
}
Problem solved. I just missed the condition:
if (keyCode == KeyEvent.KEYCODE_BACK){}
I am using a Service to play background Music. The problem is that the music continues playing when i have finished the activity.
Here is code From Main Activity which starts the service
Intent svc=new Intent(HomeActivity.this, BackgroundSoundService.class);
startService(svc);
BackgroundSoundService.java
public class BackgroundSoundService extends Service {
private static final String TAG = null;
public static MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.d("atMedia", "Backround Music playing");
player = MediaPlayer.create(this, R.raw.background);
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() {
super.onDestroy();
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
Try to stop service from your MainActivity:
Intent svc=new Intent(HomeActivity.this, BackgroundSoundService.class);
stopService(svc);
You have to call selfStop() method inside your service.
or use stopService() API