Android 使用Service和Broadcast播放音乐文件
2010-11-05 00:57:58 来源:WEB开发网 闂傚倸鍊搁崐鎼佸磹閹间礁纾归柟闂寸绾剧懓顪冪€n亜顒㈡い鎰Г閹便劌顫滈崱妤€骞婄紓鍌氬€瑰銊╁箟缁嬫鍚嬮柛顐線缂冩洟姊婚崒娆戭槮婵犫偓闁秵鎯為幖娣妼缁愭鏌″搴′簽濞戞挸绉甸妵鍕冀椤愵澀娌梺缁樻尪閸庣敻寮婚敐澶婂嵆闁绘劖绁撮崑鎾诲捶椤撴稑浜炬慨妯煎亾鐎氾拷

使用service播放sdcard中的一首歌曲,并在service中通过广播broadcast通知Activity更新界面。下面三个最终的图分别是:初始化时,播放时,暂停时。



界面是两个按钮,采用LinearLayout布局。代码如下:
代码
< ?xml version="1.0" encoding="utf-8"?>< LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" >< Button android:id="@+id/btnPlayOrPause" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="播放" android:layout_weight="1" android: />< Button android:id="@+id/btnStop" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="停止" android:layout_weight="1" android: />< /LinearLayout>
1.主Activity中,有四部分:onCreate()方法、onDestroy()方法、BroadcastReceiver的一个类updateUIReceiver、和按钮事件处理方法clickHandl()。
在onCreate()方法中主要是注册一个广播。注意在onCreate()里注册,记得在onDestroy()方法里解除注册。
代码
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btnStartOrPause = (Button) findViewById(R.id.btnPlayOrPause); btnStop = (Button) findViewById(R.id.btnStop); //onCreate()里注册BroadcastReceiver //onDestroy()里解除注册 //下面的"giuz.receiver.music"要在manifest.xml里注册 IntentFilter filter = new IntentFilter("giuz.receiver.music"); registerReceiver(updatUIReceiver, filter);
更多精彩
赞助商链接