1.在raw目錄放一個mp3文件:test.mp3;
2.建一個MediaPlay的Service文件MusicService.java
public class MusicService extends Service
{
//MediaPlayer對象
private MediaPlayer player;
public IBinder onBind(Intent arg0)
{
return null;
}
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
//這里可以理解為裝載音樂文件
player = MediaPlayer.create(this, R.raw.test);
//開始播放
player.start();
}
public void onDestroy()
{
super.onDestroy();
//停止音樂-停止Service
player.stop();
}
}
3.主文件
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//從main.xml布局中獲得Button對象
Button button_start = (Button)findViewById(R.id.start);
Button button_stop = (Button)findViewById(R.id.stop);
//設置按鈕(Button)監聽
button_start.setOnClickListener(start);
button_stop.setOnClickListener(stop);
}
//開始按鈕
private OnClickListener start = new OnClickListener()
{
public void onClick(View v)
{
//開啟Service
startService(new Intent("com.yarin.Android.MUSIC"));
}
};
//停止按鈕
private OnClickListener stop = new OnClickListener()
{
public void onClick(View v)
{
//停止Service
stopService(new Intent("com.yarin.Android.MUSIC"));
}
};