Android Service使用方法--简单音乐播放实例

来源:互联网 发布:水冷 风冷 知乎 编辑:程序博客网 时间:2024/05/21 19:03

Service是服务,Android里的Service跟Windows里的Service功能差不多,就是一个不可见的进程在后台执行。

Android中的服务,它与Activity不同,它是不能与用户交互的,不能自己启动的,运行在后台的程序,如果我们退出应用时,Service进程并没有结束,它仍然在后台运行,例如我们打开一个音乐播放器来听音乐,在听音乐的同时也想做下其它的事情,比如上网聊Q、或者上网浏览新闻之类的事情。这样的话,我们就需要用到Service服务了。下面我们以一个简单的音乐播放器的实例来说明下Service的生命周期和Service的使用。

下面是音乐播放器Demo的程序结构图:

Android Service 的生命周期:

Android中Service的生命周期并不是很复杂,只是继承了onCreate(), onStart(), onDestory()三个方法。当我们第一次启动Service服务时,调用onCreate() --> onStart()两个方法,当停止Service服务时,调用onDestory()方法。如果Service已经启动了,第二次再启动同一个服务时,就只是调用 onStart() 这个方法了。

Android Service 的使用:

[1] 参照上面的程序结构图,我们可以创建一个Android程序,在src目录下创建一个Activity,一个继承自Service类的服务类;同时在资源文件夹res目录下创建一个raw的文件夹存放音频文件,如把music.mp3音乐文件放在该目录下。该程序的主界面如下:

[2] layout目录下的main.xml文件的源码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView 
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:text="Welcome to Andy's blog!"
       android:textSize="16sp"/>  
    <TextView 
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:text="音乐播放服务"/>
    <Button
       android:id="@+id/startMusic"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="开启音乐播放服务"/>
    <Button
       android:id="@+id/stopMusic"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="停止音乐播放服务"/>
   <Button
      android:id="@+id/bindMusic"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="绑定音乐播放服务"/>
   <Button
      android:id="@+id/unbindMusic"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="解除 ——绑定音乐播放服务"/>
</LinearLayout>

[3] src目录下MusicService.java源码:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
packagecom.andyidea.service;
importandroid.app.Service;
importandroid.content.Intent;
importandroid.media.MediaPlayer;
importandroid.os.IBinder;
importandroid.util.Log;
importandroid.widget.Toast;
publicclass MusicService extendsService {
    //为日志工具设置标签
    privatestatic String TAG = "MusicService";
    //定义音乐播放器变量
    privateMediaPlayer mPlayer;
     
    //该服务不存在需要被创建时被调用,不管startService()还是bindService()都会启动时调用该方法
    @Override
    publicvoid onCreate() {
        Toast.makeText(this,"MusicSevice onCreate()"
                , Toast.LENGTH_SHORT).show();
        Log.e(TAG,"MusicSerice onCreate()");
         
        mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.music);
        //设置可以重复播放
        mPlayer.setLooping(true);
        super.onCreate();
    }
     
    @Override
    publicvoid onStart(Intent intent, intstartId) {
        Toast.makeText(this,"MusicSevice onStart()"
                , Toast.LENGTH_SHORT).show();
        Log.e(TAG,"MusicSerice onStart()");
         
        mPlayer.start();
         
        super.onStart(intent, startId);
    }
    @Override
    publicvoid onDestroy() {
        Toast.makeText(this,"MusicSevice onDestroy()"
                , Toast.LENGTH_SHORT).show();
        Log.e(TAG,"MusicSerice onDestroy()");
         
        mPlayer.stop();
         
        super.onDestroy();
    }
    //其他对象通过bindService 方法通知该Service时该方法被调用
    @Override
    publicIBinder onBind(Intent intent) {
        Toast.makeText(this,"MusicSevice onBind()"
                , Toast.LENGTH_SHORT).show();
        Log.e(TAG,"MusicSerice onBind()");
         
        mPlayer.start();
         
        returnnull;
    }
    //其它对象通过unbindService方法通知该Service时该方法被调用
    @Override
    publicboolean onUnbind(Intent intent) {
        Toast.makeText(this,"MusicSevice onUnbind()"
                , Toast.LENGTH_SHORT).show();
        Log.e(TAG,"MusicSerice onUnbind()");
         
        mPlayer.stop();
         
        returnsuper.onUnbind(intent);
    }
     
}

[4] src目录下MusicServiceActivity源码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
packagecom.andyidea.service;
importandroid.app.Activity;
importandroid.content.ComponentName;
importandroid.content.Context;
importandroid.content.Intent;
importandroid.content.ServiceConnection;
importandroid.os.Bundle;
importandroid.os.IBinder;
importandroid.util.Log;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
importandroid.widget.Toast;
publicclass MusicServiceActivity extendsActivity {
     
    //为日志工具设置标签
    privatestatic String TAG = "MusicService";
     
    /** Called when the activity is first created. */
    @Override
    publicvoid onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
         
        //输出Toast消息和日志记录
        Toast.makeText(this,"MusicServiceActivity",
                Toast.LENGTH_SHORT).show();
        Log.e(TAG,"MusicServiceActivity");
         
        initlizeViews();
    }
     
    privatevoid initlizeViews(){
        Button btnStart = (Button)findViewById(R.id.startMusic);
        Button btnStop = (Button)findViewById(R.id.stopMusic);
        Button btnBind = (Button)findViewById(R.id.bindMusic);
        Button btnUnbind = (Button)findViewById(R.id.unbindMusic);
         
        //定义点击监听器
        OnClickListener ocl = newOnClickListener() {
             
            @Override
            publicvoid onClick(View v) {
                //显示指定  intent所指的对象是个   service
                Intent intent = newIntent(MusicServiceActivity.this,MusicService.class);
                switch(v.getId()){
                caseR.id.startMusic:
                    //开始服务
                    startService(intent);
                    break;
                caseR.id.stopMusic:
                    //停止服务
                    stopService(intent);
                    break;
                caseR.id.bindMusic:
                    //绑定服务
                    bindService(intent, conn, Context.BIND_AUTO_CREATE);
                    break;
                caseR.id.unbindMusic:
                    //解绑服务
                    unbindService(conn);
                    break;
                }
            }
        };
         
         //绑定点击监听
        btnStart.setOnClickListener(ocl);
        btnStop.setOnClickListener(ocl);
        btnBind.setOnClickListener(ocl);
        btnUnbind.setOnClickListener(ocl);
    }
     
    //定义服务链接对象
    finalServiceConnection conn = newServiceConnection() {
         
        @Override
        publicvoid onServiceDisconnected(ComponentName name) {
            Toast.makeText(MusicServiceActivity.this,"MusicServiceActivity onSeviceDisconnected"
                    , Toast.LENGTH_SHORT).show();
            Log.e(TAG,"MusicServiceActivity onSeviceDisconnected");
        }
         
        @Override
        publicvoid onServiceConnected(ComponentName name, IBinder service) {
            Toast.makeText(MusicServiceActivity.this,"MusicServiceActivity onServiceConnected"
                    ,Toast.LENGTH_SHORT).show();
            Log.e(TAG,"MusicServiceActivity onServiceConnected");
        }
    };
}

[5] 最后,我们别忘了在AndroidManifest.xml配置文件中添加对Service的注册。即在application节点中添加

      <service android:name=".MusicService"/> 进行注册。

[6] 我们来看下程序运行后的Log.e中显示的Service生命周期

[7] 我们在Android终端设备中查看下刚才启动的音乐播放服务,看看我们退出程序后,是不是该程序的服务还在运行的呢?按如下步骤:Menu --> Settings --> Applications --> Running services 。在弹出的 Running services 中可以看到有哪些服务在运行。

这样我们就看到我们退出程序后,是由于该服务还在后台运行着,所以我们的音乐还可以继续播放着。就这样,我们就可以一边享受音乐,一边可以聊QQ,或者浏览新闻等等。

0 0
原创粉丝点击