Android使用Service播放音乐

Service播放音乐

res/layout/main.xml

MusicService.java

package com.zeph.android.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

public class MusicService extends Service {
	private MediaPlayer mMediaPlayer;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		mMediaPlayer = MediaPlayer.create(this, R.raw.music01);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		mMediaPlayer.stop();
		mMediaPlayer.release();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		int operate = intent.getIntExtra("operate", 3);
		switch (operate) {
		case 0:
			if (!mMediaPlayer.isPlaying()) {
				mMediaPlayer.start();
			}
			break;
		case 1:
			if (mMediaPlayer.isPlaying()) {
				mMediaPlayer.pause();
			}
			break;
		case 2:
			if (mMediaPlayer.isPlaying()) {
				mMediaPlayer.stop();
				mMediaPlayer = MediaPlayer.create(this, R.raw.music01);
			}
			break;
		default:
			break;
		}
	}
}

ServiceTestActivity.java

package com.zeph.android.service;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ServiceTestActivity extends Activity {
	private Button playButton;
	private Button pauseButton;
	private Button stopButton;
	private Button stopService;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		playButton = (Button) findViewById(R.id.playButton);
		pauseButton = (Button) findViewById(R.id.pauseButton);
		stopButton = (Button) findViewById(R.id.stopButton);
		stopService = (Button) findViewById(R.id.stopService);

		playButton.setOnClickListener(new ButtonOnClickListener());
		pauseButton.setOnClickListener(new ButtonOnClickListener());
		stopButton.setOnClickListener(new ButtonOnClickListener());
		stopService.setOnClickListener(new ButtonOnClickListener());
	}

	public class ButtonOnClickListener implements OnClickListener {

		@Override
		public void onClick(View view) {
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), MusicService.class);
			if (view == playButton) {
				intent.putExtra("operate", 0);
				startService(intent);
			} else if (view == pauseButton) {
				intent.putExtra("operate", 1);
				startService(intent);
			} else if (view == stopButton) {
				intent.putExtra("operate", 2);
				startService(intent);
			} else if (view == stopService) {
				stopService(intent);
			}
		}
	}
}
暂无评论
  • 1:请一针见血的评论。
  • 2:评论需要审核通过后才能显示。
  • 3:评论字数限制在1000字以内。
  • 当前字数:0
热门文章
推荐文章
随机文章
关于本站 - 广告服务 - 版权声明 - 联系我们 - 友情链接 - 网站地图 - 帮助中心