1.布局res里边加raw加背景音乐:
2.建一个MyService类继承Service,代码如下:
package com.example.day09a_05_serviceyy;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.MediaStore.Audio.Media;
//1.继承android.app.Service
//不需要绑定的Service
public class MyService_yinyue extends Service{
@Override
public IBinder onBind(Intent intent) {
return null;
}
//第二步 实现生命周期方法
@Override
public void onCreate() {
super.onCreate();
//3播放音乐
MediaPlayer player=MediaPlayer.create(getApplication(), R.raw.aaa);
player.start();
//4在AndroidManifest.xml注册
}
}
3.在主方法MainActivity里边写:
package com.example.day09a_05_serviceyy;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent=new Intent(MainActivity.this, MyService_yinyue.class);
startService(intent);
}
}
4.在清单文件里注册:
<!--4注册 -->
<service android:name="com.example.day09a_05_serviceyy.MyService_yinyue"></service>