使用Service+MediaPlayer播放音乐
res/raw/文件夹下存放mp3资源: 。略
MainActivity布局代码:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.mrzhao.servicemusicdemo.MainActivity"> <Button android:id="@+id/start_bt" android:layout_width="match_parent" android:text="开始播放" android:onClick="onClick" android:layout_height="wrap_content" /> <Button android:id="@+id/pause_bt" android:layout_width="match_parent" android:text="暂停播放" android:onClick="onClick" android:layout_height="wrap_content" /> <Button android:id="@+id/stop_bt" android:layout_width="match_parent" android:text="停止播放" android:onClick="onClick" android:layout_height="wrap_content" /> </LinearLayout>
定义一个服务Service:
public class MusicService extends Service { private MediaPlayer mediaPlayer; public MusicService() { } @Override public IBinder onBind(Intent intent) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { int type = intent.getIntExtra("type", 0); switch (type) { case 1: //开始播放音乐 startPlay(); break; case 2: //暂停 pausePlay(); break; case 3: //停止 stopPlay(); break; } return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); //服务停止的时候停止播放并释放资源 stopPlay(); } /** * 开始播放 */ public void startPlay() { if (mediaPlayer == null){ //初始化音乐播放器 mediaPlayer = MediaPlayer.create(this, R.raw.pfzl); } if (mediaPlayer != null && !mediaPlayer.isPlaying()) { mediaPlayer.start(); } } /** * 暂停播放 */ public void pausePlay() { if (mediaPlayer != null && mediaPlayer.isPlaying()) { mediaPlayer.pause(); } } /** * 停止播放 */ public void stopPlay() { if (mediaPlayer != null && mediaPlayer.isPlaying()) { mediaPlayer.stop(); //停止的时候释放资源 mediaPlayer.release(); mediaPlayer = null; } } }
MainActivity 文件:
public class MainActivity extends AppCompatActivity { private Intent intent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); intent = new Intent(this,MusicService.class); } public void onClick(View view) { switch (view.getId()){ case R.id.start_bt: intent.putExtra("type",1); break; case R.id.pause_bt: intent.putExtra("type",2); break; case R.id.stop_bt: intent.putExtra("type",3); break; } startService(intent); } }