1.我们播放音乐,希望在后台长期运行,不希望因为内存不足等等原因,从而导致被gc回收,音乐播放终止,所以我们这里使用服务Service创建一个音乐播放器。
2.创建一个音乐播放器项目(使用服务)
(1)首先新建一个Android项目,命名为"Mp3音乐播放器",如下:
(2)创建服务MusicService,如下:
package com.himi.Mp3player; import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder; public class MusicService extends Service {
/**
* 要播放的音乐文件的路径
*/
private String path;
private MediaPlayer mediaPlayer;
/**
* 音乐播放的状态
*/
private int PLAYING_STATUS;
private int STOP = 0;
private int PLAYING = 1;
private int PAUSE = 2; @Override
public IBinder onBind(Intent intent) {
return new MyBinder();
} private class MyBinder extends Binder implements IMusicService {
public MusicService callGetMusicService() {
return getMusicService();
}
} /**
* 返回服务的对象
*
* @return
*/
public MusicService getMusicService() {
return this;
} @Override
public void onCreate() {
System.out.println("服务被创建了。");
super.onCreate();
} @Override
public void onDestroy() {
System.out.println("服务被销毁了。");
super.onDestroy();
} /**
* 设置要播放的音乐
*
* @param path
* 音乐文件的路径
*/
public void setMusic(String path) {
this.path = path;
} /**
* 播放音乐,播放之前请设置音乐的路径
*/
public boolean play() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
try {
if (path == null) {
return false;
}
mediaPlayer = new MediaPlayer();
mediaPlayer.reset();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();
mediaPlayer.start();
PLAYING_STATUS = PLAYING;
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} /**
* 暂停音乐
*/
public void pause() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
PLAYING_STATUS = PAUSE;
}
} /**
* 继续开始
*/
public void resume() {
if (mediaPlayer != null && PLAYING_STATUS == PAUSE) {
mediaPlayer.start();
PLAYING_STATUS = PLAYING;
}
} public void stop() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
PLAYING_STATUS = STOP;
}
}
}
使用到的接口为IMusicService,如下:
这里服务(service)方法比较多,所以我们最好调用方法获取服务的引用,如下:
package com.himi.Mp3player; public interface IMusicService {
//调用获取服务的引用
public MusicService callGetMusicService(); }
(3)布局文件activity_main.xml,如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.himi.Mp3player.MainActivity" > <EditText
android:id="@+id/et_path"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入音乐的路径" /> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" > <Button
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="play"
android:text="播放" /> <Button
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="pause"
android:text="暂停" /> <Button
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="resume"
android:text="继续" /> <Button
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="stop"
android:text="停止" />
</LinearLayout> </LinearLayout>
布局效果如下:
(4)使用到服务要在AndroidMainfest.xml文件中注册服务,如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.himi.Mp3player"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="17" /> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.himi.Mp3player.MusicService"></service>
</application> </manifest>
(5)此处的MainActivity,如下:
package com.himi.Mp3player; import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast; public class MainActivity extends Activity { private MyConn conn;
private IMusicService iMusicService;
private MusicService musicService;
private EditText et_path; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); et_path = (EditText) findViewById(R.id.et_path);
// 保证服务长期后台运行
Intent intent = new Intent(this, MusicService.class);
startService(intent);
// 调用服务的方法
conn = new MyConn();
bindService(intent, new MyConn(), BIND_AUTO_CREATE);
} private class MyConn implements ServiceConnection { public void onServiceConnected(ComponentName name, IBinder service) {
iMusicService = (IMusicService) service;
musicService = iMusicService.callGetMusicService();
} public void onServiceDisconnected(ComponentName name) {
// TODO 自动生成的方法存根 } } public void play(View view) {
String path = et_path.getContext().toString().trim();
if (TextUtils.isEmpty(path)) {
Toast.makeText(this, "路径不合法", 0).show();
return;
}
musicService.setMusic(path);
boolean result = musicService.play();
if (!result) {
Toast.makeText(this, "播放失败,请检查路径,或者音乐文件是否合法", 0).show();
}
} public void pause(View view) {
musicService.pause();
} public void resume(View view) {
musicService.resume(); } public void stop(View view) {
musicService.stop();
} @Override
protected void onDestroy() {
// 解绑服务
unbindService(conn);
super.onDestroy();
} }