android service 学习
2010-08-23 01:13:00 来源:WEB开发网首先要定义一个Receiver,并继承BroadcastReceiver,然后在AndroidManifest.xml中进行注册:
view sourceprint?1
2
3
4
5
Receiver的实现:
MusicReceiver.java
view sourceprint?01/**
02 * @author allin.dev
03 * http://allin.cnblogs.com/
04 *
05 */
06public class MusicReceiver extends BroadcastReceiver {
07
08 private static final String TAG = "MusicReceiver";
09 @Override
10 public void onReceive(Context context, Intent intent) {
11 Log.d(TAG, "onReceive");
12 Intent it = new Intent("org.allin.android.musicService");
13 Bundle bundle = intent.getExtras();
14 it.putExtras(bundle);
15
16 if(bundle != null){
17 int op = bundle.getInt("op");
18 if(op == 4){
19 context.stopService(it);
20 }else{
21 context.startService(it);
22 }
23 }
24
25 }
26
27}
然后对PlayMusic中的onclick方法进行些改造,把Intent指向Receiver
Intent intent = new Intent("org.allin.android.musicReceiver");
intent中绑定的操作码都不变,再调用sendBroadcast(intent);把intentg广播出去。
当MusicReceiver接受到广播后根据操作码进行相应的操作。
接下来的例子就是使用bindService来启动Service
首先一样是写一个Activity
view sourceprint?01public class PlayBindMusic extends Activity implements OnClickListener {
02
03 private static final String TAG = "PlayBindMusic";
04 private Button playBtn;
05 private Button stopBtn;
06 private Button pauseBtn;
07 private Button exitBtn;
08
09 private BindMusicService musicService;
10
11 @Override
更多精彩
赞助商链接