一个简单的Android音乐播放器

来源:互联网 发布:女生衬衫品牌知乎 编辑:程序博客网 时间:2024/06/10 04:52

在这里主要是用两个简单的按钮实现音乐的播放和停止功能,工程的目录结构为:

工程的目录结构图

同时添加一个文件夹,里面放后缀为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";@Overridepublic 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;@Overridepublic 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();}@Overridepublic 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);}@Overridepublic void onDestroy() {Toast.makeText(this, "MusicSevice onDestroy()", Toast.LENGTH_SHORT).show();Log.e(TAG, "MusicSerice onDestroy()");mPlayer.stop();super.onDestroy();}@Overridepublic IBinder onBind(Intent intent) {return null;}}

效果图为:

音乐播放效果图

0 0