1) First put your music.mp3 into raw folder
2) Declaring a service in the manifest as child of the <application>
element
<service android:name=".SoundService" android:enabled="true"/>
3) Add MusicService.java
class:
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
public class SoundService extends Service {
MediaPlayer mPlayer;
@Override
public void onCreate() {
mPlayer = MediaPlayer.create(this, R.raw.music);
mPlayer.setLooping(true);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mPlayer.start();
return Service.START_NOT_STICKY;
}
@Override
public void onDestroy() {
mPlayer.stop();
mPlayer.release();
super.onDestroy();
}
}
4) Run\Stop services in the activity:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
startService(new Intent(MainActivity.this, SoundService.class));
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onBackPressed() {
stopService(new Intent(MainActivity.this, SoundService.class));
super.onBackPressed();
}
@Override
protected void onPause() {
// When the app is going to the background
stopService(new Intent(MainActivity.this, SoundService.class));
super.onPause();
}
@Override
protected void onDestroy() {
// when system temporarily destroying activity
stopService(new Intent(MainActivity.this, SoundService.class));
super.onDestroy();
}
}