概述
//添加获得sd卡的状态权限,和读取sd卡的权限 <uses- permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <uses- permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> // MainActivity中用三个按钮,播放,暂停,停止,发送服务到后台服务来控制 public class MainActivity extends Activity implements OnClickListener { private Button puase; private Button stop; private Button start; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); start = (Button) findViewById(R.id.start); puase = (Button) findViewById(R.id.puase); stop = (Button) findViewById(R.id.stop); start.setOnClickListener(this); puase.setOnClickListener(this); stop.setOnClickListener(this); } @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, Service1.class); switch (v.getId()) { case R.id.start: intent.putExtra("key", 1); break; case R.id.puase: intent.putExtra("key", 2); break; case R.id.stop: intent.putExtra("key", 3); break; default: break; } startService(intent); } } //自定义类,继承Service服务 public class Service1 extends Service { private MediaPlayer mediaplayer; private ArrayList<Music> list; private String path = ""; private int index = 0; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); mediaplayer = new MediaPlayer(); list = new ArrayList<Music>(); //读取SD卡 if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { File file = Environment.getExternalStorageDirectory(); path = file.getAbsolutePath(); } list.add(new Music("男人歌", path + "/nanrenge.mp3")); list.add(new Music("夜色", path + "/yese.mp3")); list.add(new Music("漂洋过海来看你", path + "/piaoyang.mp3")); list.add(new Music("兄弟无数", path + "/xiongdiwushu.mp3")); //播放完成后自定播放下一曲 mediaplayer.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { index++; play(); } }); } //用这个方法控制MainActivity发来的服务,控制音乐 @Override public int onStartCommand(Intent intent, int flags, int startId) { int m = intent.getIntExtra("key", 0); switch (m) { case 1: play(); break; case 2:// 暂停 if (mediaplayer != null && mediaplayer.isPlaying()) mediaplayer.pause(); break; case 3:// 停止 if (mediaplayer != null) { mediaplayer.stop(); stopService(intent); } break; default: break; } return super.onStartCommand(intent, flags, startId); } //播放音乐 private void play() { mediaplayer.reset(); try { mediaplayer.setDataSource(list.get(index).getPath()); mediaplayer.prepare(); } catch (Exception e) { e.printStackTrace(); } mediaplayer.start(); } @Override public void onDestroy() { super.onDestroy(); if (mediaplayer != null) { mediaplayer.release(); mediaplayer = null; } } }
最后
以上就是执着棒球为你收集整理的Service后台服务控制音乐的播放暂停和停止,播放完自动播放下一曲的全部内容,希望文章能够帮你解决Service后台服务控制音乐的播放暂停和停止,播放完自动播放下一曲所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复