第一步:在MainActivity中获取XML中的组件并初始化界面点击事件,在MainActivity建一个ActivityReceiver继承BroadcastReceiver用以监听歌曲状态的变化从而更新UI,代码如下:
public class MainActivity extends Activity implements View.OnClickListener{ TextView title,author,situation; Button play,stop; // 播放控制开始结束控制ACTION public static final String CTL_ACTION = "com.example.service_musicplayer.ctl_action"; // 歌曲播放状态ACTION public static final String UPDATE_ACTION = "com.example.service_musicplayer.update_action"; ActivityReceiver activityReceiver; //定义播放状态 0x11代表没有播放 0x12 代表正在播放 0x13代表暂停 int status = 0x11; // 存放歌曲名 String titleStr[] = {"Music-1","Music-2","Music-3"}; // 存放歌手名 String authorStr[] = {"author-1","author-2","author-3"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); play = (Button) findViewById(R.id.play); stop = (Button) findViewById(R.id.stop); title = (TextView) findViewById(R.id.title); author = (TextView) findViewById(R.id.author); situation = (TextView) findViewById(R.id.situation); play.setOnClickListener(this); stop.setOnClickListener(this); // 使用代码方式为broadcastReceiver注册监听 activityReceiver = new ActivityReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(UPDATE_ACTION); // 注册broadcastReceiver registerReceiver(activityReceiver,intentFilter); Intent intent = new Intent(this,MusicService.class); startService(intent); } @Override public void onClick(View v) { Intent intent = new Intent(); intent.setAction(CTL_ACTION); switch (v.getId()){ case R.id.play: intent.putExtra("control",1); break; case R.id.stop: intent.putExtra("control",2); break; }
<span style="white-space:pre"> </span>sendBroadcast(intent); } // 自定义BroadcastReceiver 监听Servicec传来的广播 public class ActivityReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { String str = ""; int update = intent.getIntExtra("update",-1); int current = intent.getIntExtra("current",-1); if(current >= 0){ title.setText(titleStr[current]); author.setText(authorStr[current]); } switch (update){ case 0x11: // status = 0x11; str = "未播放"; break; case 0x12: // status = 0x12; str = "正在播放"; break; case 0x13: // status = 0x13; str = "暂停"; break; } situation.setText(str); } }}
第二步:新建MusicService继承Service,MusicService中建了一个MyReceiver类继承BroadcastReceiver类用以监听歌曲播放状态的变化,以广播的方式将歌曲播放状态发出,在MainActivity中的ActivityReceiver能监听到此状态变化来更新UI,代码如下:
<span style="font-size:18px;">public class MusicService extends Service {
String musics[] = new String[]{"Leo Kayyu - Nokia Tune(Remix).mp3", "canon.mp3", "Cvked - iphone(Caked Up Mashup).mp3"};
int current = 0;
int status = 0x11; // 0x11不在播放状态 0x12正在播放 0x13暂停播放
MediaPlayer mediaPlayer;
AssetManager am;
MyReceiver serviceReceiver;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
am = getAssets();
serviceReceiver = new MyReceiver();
// 代码方式为MyReceiver注册
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(MainActivity.CTL_ACTION);
registerReceiver(serviceReceiver,intentFilter);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
current++;
if(current>=3) {
current = 0;
}
Intent sendIntent = new Intent(MainActivity.UPDATE_ACTION);
sendIntent.putExtra("current",current);
sendBroadcast(sendIntent);
prepareAndPlay(musics[current]);
}
});
}
// 监听歌曲的播放状态,在歌曲播放状态改变时触发
public class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
int control = intent.getIntExtra("control",-1);
switch(control){
case 1:
//原来是没播放的状态
if(status == 0x11){
prepareAndPlay(musics[current]);
status = 0x12;
//原来处于播放状态
}else if(status == 0x12){
mediaPlayer.pause();
status = 0x13;
// 原来处于暂停状态
}else if(status == 0x13){
mediaPlayer.start();
status = 0x12;
}
break;
case 2:
// 原来在播放或暂停状态
if(status == 0x12 || status == 0x13){
mediaPlayer.stop();
status = 0x11;
}
break;
}
Intent sendIntent = new Intent(MainActivity.UPDATE_ACTION);
sendIntent.putExtra("update",status);
sendIntent.putExtra("current",current);
sendBroadcast(sendIntent);
}
}
public void prepareAndPlay(String music){
try {</span>
<span style="font-size:18px;"><span style="white-space:pre"> </span> mediaPlayer.reset(); AssetFileDescriptor afd = am.openFd(URLEncoder.encode(music,"utf-8")); mediaPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength()); // 准备声音 mediaPlayer.prepare(); // 播放 mediaPlayer.start(); } catch (IOException e) { e.printStackTrace(); } }}</span>附:程序的布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.service_musicplayer.MainActivity">
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="歌名"
android:textSize="20dp"/>
<Button
android:id="@+id/play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="play"
android:layout_below="@+id/title"/>
<Button
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="stop"
android:layout_toRightOf="@+id/play"
android:layout_alignBaseline="@+id/play"/>
<TextView
android:id="@+id/author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/play"
android:text="作者/歌手"
android:textSize="20dp"/>
<TextView
android:id="@+id/situation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/play"
android:text="播放状态"
android:textSize="20dp"
android:layout_toRightOf="@+id/author"
android:layout_marginLeft="20dp"/>
</RelativeLayout>
运行界面如下:
<service android:name=".MusicService"/>(以上代码参照了安卓疯狂讲义,但是书上没讲音频文件应该放在哪里,自己新添了播放状态TextView)
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。