六、service播放音樂
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>