android service 学习
2010-08-23 01:13:00 来源:WEB开发网下面是整个应用启动界面:
先从使用startService启动Service学起
首先编写一个Activity
view sourceprint?01public class PlayMusic extends Activity implements OnClickListener {
02 private static final String TAG = "PlayMusic";
03 private Button playBtn;
04 private Button stopBtn;
05 private Button pauseBtn;
06 private Button exitBtn;
07 private Button closeBtn;
08
09 //....(详见源码)
10
11@Override
12 public void onClick(View v) {
13 int op = -1;
14 Intent intent = new Intent("org.allin.android.musicService");
15
16 //广播用
17// Intent intent = new Intent("org.allin.android.musicReceiver");
18
19 switch (v.getId()) {
20 case R.id.play:
21 Log.d(TAG, "onClick: playing muic");
22 op = 1;
23 break;
24 case R.id.stop:
25 Log.d(TAG, "onClick: stoping music");
26 op = 2;
27 break;
28 case R.id.pause:
29 Log.d(TAG, "onClick: pausing music");
30 op = 3;
31 break;
32 case R.id.close:
33 Log.d(TAG, "onClick: close");
34 this.finish();
35 break;
36 case R.id.exit:
37 Log.d(TAG, "onClick: exit");
38 op = 4;
39 stopService(intent);
40 this.finish();
41 break;
42 }
43
44 Bundle bundle = new Bundle();
45 bundle.putInt("op", op);
46 intent.putExtras(bundle);
47 startService(intent);
48
49// sendBroadcast(intent);
50 }
51
52
53}
通过重写onClick方法来实现对播放音乐的控制。这里把播放音乐的各种操作用数字的方式通过Intent传递给service。
更多精彩
赞助商链接