android service 学习
2010-08-23 01:13:00 来源:WEB开发网构造一个Intent ,ntent intent = new Intent("org.allin.android.musicService");
"org.allin.android.musicService"是在AndroidManifest.xml文件中对service类的定义
view sourceprint?1
2
3
4
5
把操作码放在Bundle中
Bundle bundle = new Bundle();
bundle.putInt("op", op);
intent.putExtras(bundle);
最后使用startService(intent);启动服务。
下面看看Service是怎么实现的。
MusicService.java
view sourceprint?01/**
02 * @author allin.dev
03 * http://allin.cnblogs.com/
04 *
05 */
06public class MusicService extends Service {
07
08 private static final String TAG = "MyService";
09 private MediaPlayer mediaPlayer;
10
11 /*
12 * (non-Javadoc)
13 *
14 * @see android.app.Service#onBind(android.content.Intent)
15 */
16 @Override
17 public IBinder onBind(Intent arg0) {
18 return null;
19 }
20
21 @Override
22 public void onCreate() {
23 Log.v(TAG, "onCreate");
24 if (mediaPlayer == null) {
25 mediaPlayer = MediaPlayer.create(this, R.raw.tmp);
26 mediaPlayer.setLooping(false);
27 }
28 }
29
30 @Override
31 public void onDestroy() {
32 Log.v(TAG, "onDestroy");
33 if (mediaPlayer != null) {
34 mediaPlayer.stop();
35 mediaPlayer.release();
36 }
37 }
38
39 @Override
40 public void onStart(Intent intent, int startId) {
41 Log.v(TAG, "onStart");
42 if (intent != null) {
43 Bundle bundle = intent.getExtras();
44 if (bundle != null) {
赞助商链接