这里主要是用两个简单的按钮实现音乐的播放和停止功能,工程的目录结构为:
同时添加一个文件夹,里面放后缀为mp3的文件就可以了。
在main配置文件主要是添加两个Button:
添加一个activity类和一个service类AndroidManifest.xml配置文件为:
创建一个MusicServiceActivity类启动service类:
package com.basi;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;public class MusicServiceActivity extends Activity { private static String TAG = "MusicService"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Toast.makeText(this, "MusicServiceActivity", Toast.LENGTH_SHORT).show(); Log.e(TAG, "MusicServiceActivity"); initlizeViews(); } private void initlizeViews() { Button btnStart = (Button) findViewById(R.id.startMusic); Button btnStop = (Button) findViewById(R.id.stopMusic); OnClickListener ocl = new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(MusicServiceActivity.this, MusicService.class); switch (v.getId()) { case R.id.startMusic: // 开始服务 startService(intent); break; case R.id.stopMusic: // 停止服务 stopService(intent); break; } } }; btnStart.setOnClickListener(ocl); btnStop.setOnClickListener(ocl); }}
service类代码为:
package com.basi;import android.app.Service;import android.content.Intent;import android.media.MediaPlayer;import android.os.IBinder;import android.util.Log;import android.widget.Toast;public class MusicService extends Service { private static String TAG = "MusicService"; private MediaPlayer mPlayer; @Override public void onCreate() { Toast.makeText(this, "MusicSevice onCreate()", Toast.LENGTH_SHORT) .show(); Log.e(TAG, "MusicSerice onCreate()"); mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.a); // 设置可以重复播放 mPlayer.setLooping(true); super.onCreate(); } @Override public void onStart(Intent intent, int startId) { Toast.makeText(this, "MusicSevice onStart()", Toast.LENGTH_SHORT) .show(); Log.e(TAG, "MusicSerice onStart()"); mPlayer.start(); super.onStart(intent, startId); } @Override public void onDestroy() { Toast.makeText(this, "MusicSevice onDestroy()", Toast.LENGTH_SHORT) .show(); Log.e(TAG, "MusicSerice onDestroy()"); mPlayer.stop(); super.onDestroy(); } @Override public IBinder onBind(Intent intent) { return null; }}
效果图为: