Posted on 2009-11-04 13:48
疯狂 阅读(3182)
评论(2) 编辑 收藏 所属分类:
android
学习android阶段写的一个例子,先将代码和解析贴出来,如有不对,欢迎指示!
最终界面很简单:
主要结构:
activity 和service通过互相通话来保持播放和界面状态:
代码主要代码:MyPlayer.java(界面) ,MusicPlayService(service) ,IntentParam(参数)
MyPlayer.java:
package com.myplayer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MyPlayer extends Activity implements OnClickListener {
Button playpausebn;
Button stopbn;
OnClickListener clickListener;
Uri nowPlay;
int status;
UpdateReceiver receiver;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);// 添加界面
playpausebn = (Button) findViewById(R.id.palypause);// 获取播放暂停按钮
stopbn = (Button) findViewById(R.id.stop);// 获取停止按钮
// 解析歌曲路径,service 通过uri创建MediaPlayer
nowPlay = Uri
.parse("http://julysky.wz66.com/uploadfiles/2007-3/321388085.mp3");//这里播放的是暗(*^__^*) 嘻嘻……
// 给按钮添加监听,用来控制播放
playpausebn.setOnClickListener(this);
stopbn.setOnClickListener(this);
// 添加广播接收器 也就是用来接收sevice传过来的数据 intent
receiver = new UpdateReceiver();
// 添加过滤器 只接收
IntentFilter filter = new IntentFilter();
filter.addAction(IntentParam.TO_ACTIVITY);
registerReceiver(receiver, filter);// 注册接收器
// service自己不能启动 是由当前activity上下文启动 此时会调用service的oncreate方法初始化service
startService(new Intent(this, MusicPlayService.class));
}
// 实现onclickListener的方法
public void onClick(View v) {
if (nowPlay == null) {
return;
}
int cmd = 0;
Intent intent = new Intent(IntentParam.TO_SERVICE);// 创建意图,通知service
// 根据cmd命令控制后台音乐的播放
switch (v.getId()) {
case R.id.palypause:// 如果点击了暂停和播放按钮
if (status == IntentParam.STATUS_PLAYING) {// 并且当前状态时播放,就暂停
cmd = IntentParam.CMD_PAUSE;// 暂停命令
} else if (status == IntentParam.STATUS_STOPPED
|| status == IntentParam.STATUS_PAUSED) {// 并且当前状态时暂停或停止,就播放
intent.setData(nowPlay);// 给意图添加数据,也就是将音乐uri传给service
cmd = IntentParam.CMD_PLAY;// 播放命令
} else {
cmd = IntentParam.CMD_STOP;
}
break;
case R.id.stop:
cmd = IntentParam.CMD_STOP;// 停止命令
default:
break;
}
intent.putExtra("cmd", cmd);// 将命令放入意图
sendBroadcast(intent);// 播出意图
}
// 广播接收器接收service传来的消息 根据service传来的音乐播放状态 来跟新界面
public class UpdateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
status = intent.getIntExtra("status", -1);// 获取状态
switch (status) {
case IntentParam.STATUS_PLAYING:// 播放状态
playpausebn.setText(R.string.pause);// 这里简单的修改按钮的文字,
break;
case IntentParam.STATUS_PAUSED:
case IntentParam.STATUS_STOPPED:
playpausebn.setText(R.string.play);
break;
default:
break;
}
}
}
}
MusicPlayService:
package com.myplayer;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.IBinder;
public class MusicPlayService extends Service {
int status;
MediaPlayer mp;
OnCompletionListener completionListener;
CommandReceiver commandReceiver;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
mp = new MediaPlayer();
//初始化播放状态为停止
status = IntentParam.STATUS_STOPPED;
//注册来自activity传来的命令接收器
commandReceiver = new CommandReceiver();
//添加过滤
IntentFilter filter1 = new IntentFilter();
filter1.addAction(IntentParam.TO_SERVICE);
filter1.addDataScheme("http");
IntentFilter filter2 = new IntentFilter();
filter2.addAction(IntentParam.TO_SERVICE);
//注册接收器
registerReceiver(commandReceiver, filter1);
registerReceiver(commandReceiver, filter2);
//初始化音乐播放完毕的处理事情,通知界面跟新
completionListener = new OnCompletionListener(){
public void onCompletion(MediaPlayer mplayer) {
mplayer.stop();
status = IntentParam.STATUS_STOPPED;
updateUi();
}
};
}
//根据初始化状态 初始化界面 这里可以根据status来控制
@Override
public void onStart(Intent intent, int startId) {
updateUi();
}
@Override
public void onDestroy() {
//释放资源
unregisterReceiver(commandReceiver);
mp.release();
}
//构建接收器
public class CommandReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getIntExtra("cmd", -1)) {
case IntentParam.CMD_PLAY://如果界面传来命令是播放
Uri media = intent.getData();//获取activity传来的intent里面的数据
if (media != null) {//如果已经有音乐在播放 就释放 才行构建
mp.release();
mp = MediaPlayer.create(context, media);
mp.setOnCompletionListener(completionListener);//添加播放完毕的处理事件
try {
mp.start();//开始播放
} catch (Exception e) {
e.printStackTrace();
}
} else {
mp.start();
}
status = IntentParam.STATUS_PLAYING;
break;
case IntentParam.CMD_PAUSE:
mp.pause();
status = IntentParam.STATUS_PAUSED;
break;
case IntentParam.CMD_STOP:
mp.stop();
status = IntentParam.STATUS_STOPPED;
break;
default:
break;
}
updateUi();//根据当前的状态 通知界面跟新
}
}
//通知界面根性也就是将意图发出去让界面接收
private void updateUi() {
Intent intent = new Intent(IntentParam.TO_ACTIVITY);
intent.putExtra("status", status);
sendBroadcast(intent);
}
}
IntentParam:
package com.myplayer;
public class IntentParam {
public static final int CMD_PLAY = 0;
public static final int CMD_PAUSE = 1;
public static final int CMD_STOP = 2;
public static final int STATUS_PLAYING = 0;
public static final int STATUS_PAUSED = 1;
public static final int STATUS_STOPPED = 2;
public static final String TO_SERVICE = "toService";
public static final String TO_ACTIVITY = "toActivity";
}
另外就是AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myplayer"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".MyPlayer"
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="MusicPlayService" android:process=":remote"></service>//添加service
</application>
<uses-sdk android:minSdkVersion="4" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>//添加权限
</manifest>
完整代码下载:(晕,不知道这里什么地方可以放代码下载!!!)
放到google上不知道能不能下载:
http://infojj.googlegroups.com/web/myplayer.rar?hl=zh-CN&gda=OQGoLz8AAABJFYDHK64yE3Lf8rmWTTkKKuZHDK1BZ-D4nJlRz2lseLjh9f496UMDItX0DkmsAJ2ccyFKn-rNKC-d1pM_IdV0&gsc=ccLByiEAAAAyTazefkXbIBkLj9dbvmKyYyEKXZEdBEdpC0MvbzBM00zfKN-m9S9niuHrq-IEXAE