//先在res下建一个文件夹raw,将音乐放入其中
//以一个为例
//myhome.mp3
//在Xml中添加3个按钮
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="播放" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="暂停" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="停止" />
//可以先键ServiceDDDD,继承Service
public class ServiceDDDD extends Service {
private MediaPlayer mediaPlayer;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
mediaPlayer = MediaPlayer.create(this, R.raw.myhome);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
int extra = intent.getIntExtra("command", 0);
switch (extra) {
case 1:
mediaPlayer.start();
break;
case 2:
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
break;
case 3:
if (mediaPlayer != null) {
mediaPlayer.stop();
}
break;
default:
break;
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
}
//MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
private Button button1, button2, button3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(this, ServiceDDDD.class);
switch (arg0.getId()) {
case R.id.button1:
intent.putExtra("command", 1);
break;
case R.id.button2:
intent.putExtra("command", 2);
break;
case R.id.button3:
intent.putExtra("command", 3);
break;
default:
break;
}
startService(intent);
}
}