This is tested in android studio 2.2.3
1) first copy and paste your music.mp3
into app.res.raw
.
2) set service into AndroidManifest.xml
be like this:
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
:
:
<service android:name=".SoundService" android:enabled="true"></service>
</application>
3) Add SoundService.java
file with contain this code:
package com.jahanweb.ring;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
public class SoundService extends Service {
MediaPlayer player;
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
player = MediaPlayer.create(this, R.raw.music); //select music file
player.setLooping(true); //set looping
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return Service.START_NOT_STICKY;
}
public void onDestroy() {
player.stop();
player.release();
stopSelf();
super.onDestroy();
}
}
4) use it in the activity be like this:
package com.jahanweb.ring;
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) {
//start service and play music
startService(new Intent(MainActivity.this, SoundService.class));
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
protected void onDestroy() {
//stop service and stop music
stopService(new Intent(MainActivity.this, SoundService.class));
super.onDestroy();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…