Service应用

Service的生命周期

Service对象不能自己启动,需要通过某个ActivityService或者其他Context对象来启动。启动的方法有两种,Context.startServiceContext.bindService()。两种方式的生命周期是不同的,具体如下所示。

Context.startService方式的生命周期:
启动时,startService –> onCreate() –> onStart()
停止时,stopService –> onDestroy()

Context.bindService方式的生命周期:
绑定时,bindService  -> onCreate() –> onBind()
解绑定时,unbindService –>onUnbind() –> onDestory()

 

Service的生命周期方法比Activity少一些,只有onCreate, onStart, onDestroy 
我们有两种方式启动一个Service,他们对Service生命周期的影响是不一样的。

1
通过startService
Service
会经历 onCreate --> onStart
stopService
的时候直接onDestroy

如果是 调用者 直接退出而没有调用stopService的话,Service会一直在后台运行。
下次调用者再起来仍然可以stopService

2
通过bindService Service会经历 onCreate --> onStart
Service
只会运行onCreate, 不会调用onStart. 这个时候 调用者和Service绑定在一起.
调用者退出了,Srevice就会调用onUnbind-->onDestroyed
所谓绑定在一起就共存亡了。


注意:ServiceonCreate的方法只会被调用一次,就是你无论多少次的startServicebindServiceService只被创建一次。
如果先是bind了,那么start的时候就直接运行ServiceonStart方法,
如果先是start,那么bind的时候就直接运行onBind方法。如果你先bind上了,就stop不掉了,
只能先UnbindService, stopService,所以是先start还是先bind行为是有区别的。 http://dev.10086.cn/cmdn/wiki/index.php?doc-view-7180.html

了解了以上内容后,首先在res下新建文件夹,命名为raw,然后放入jn,mp3文件,然后开始建立工程.
step1:创建android工程,命名为MainActivity.
step2:设置UI界面,各种配置布局文件如下
main.xml
main.xml
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="fill_parent"
 4     android:layout_height="fill_parent"
 5     android:orientation="vertical" >
 6 
 7     <TextView
 8         android:layout_width="fill_parent"
 9         android:layout_height="wrap_content"
10         android:text="@string/hello" />
11     <Button 
12         android:id="@+id/startbutton"
13         android:layout_width="fill_parent"
14         android:layout_height="wrap_content"
15         android:text="@string/startbutton"/>
16     <Button 
17         android:id="@+id/stopbutton"
18         android:layout_width="fill_parent"
19         android:layout_height="wrap_content"
20         android:text="@string/stopbutton"/>
21     <Button 
22         android:id="@+id/bindbutton"
23         android:layout_width="fill_parent"
24         android:layout_height="wrap_content"
25         android:text="@string/bindbutton"/>
26     <Button 
27         android:id="@+id/unbindbutton"
28         android:layout_width="fill_parent"
29         android:layout_height="wrap_content"
30         android:text="@string/unbindbutton"/>
31     
32 
33 </LinearLayout>

strings.xml
strings.xml
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <resources>
 3 
 4     <string name="hello">Hello World, MainActivity!</string>
 5     <string name="app_name">MainActivity</string>
 6     <string name="startbutton">startbutton</string>
 7     <string name="stopbutton">stopbutton</string>
 8     <string name="bindbutton">bindbutton</string>
 9     <string name="unbindbutton">unbindbutton</string>
10     
11 
12 </resources>

AndroidManifest.xml (在AndroidManifest.xml添加用到的Service名.)
AndroidManifest.xml
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 3     package="com.cb.service"
 4     android:versionCode="1"
 5     android:versionName="1.0" >
 6 
 7     <uses-sdk android:minSdkVersion="10" />
 8 
 9     <application
10         android:icon="@drawable/ic_launcher"
11         android:label="@string/app_name" >
12         <activity
13             android:label="@string/app_name"
14             android:name=".MainActivity" >
15             <intent-filter >
16                 <action android:name="android.intent.action.MAIN" />
17 
18                 <category android:name="android.intent.category.LAUNCHER" />
19             </intent-filter>
20         </activity>
21 
22         <!-- 在Manifest.xml配置文件中添加要使用的service -->
23         <service android:name="MusicService" >
24         </service>
25     </application>
26 
27 </manifest>

step3:
1.以下给出MusicService.java,这个类用来定义Service方法
MusicService.java
 1 package com.cb.service;
 2 
 3 import android.app.Service;
 4 import android.content.Intent;
 5 import android.media.MediaPlayer;
 6 import android.os.IBinder;
 7 import android.util.Log;
 8 import android.widget.Toast;
 9 
10 public class MusicService extends Service {
11     private String TAG = "MusicService";
12     private MediaPlayer mediaPlayer;
13 
14     @Override
15     public void onCreate() {
16         super.onCreate();
17         Toast.makeText(this, "onCreate()", Toast.LENGTH_SHORT).show();
18         Log.i(TAG, "onCreate()");
19         mediaPlayer = MediaPlayer.create(MusicService.this, R.raw.jn);
20         mediaPlayer.setLooping(true);
21     }
22 
23     @Override
24     public void onStart(Intent intent, int startId) {
25         super.onStart(intent, startId);
26         Toast.makeText(this, "onStart()", Toast.LENGTH_SHORT).show();
27         Log.i(TAG, "onStart()");
28         mediaPlayer.start();
29     }
30 
31     @Override
32     public void onDestroy() {
33         super.onDestroy();
34         Toast.makeText(this, "onDestroy()", Toast.LENGTH_SHORT).show();
35         Log.i(TAG, "onDestroy()");
36         mediaPlayer.stop();
37     }
38 
39     @Override
40     public IBinder onBind(Intent intent) {
41         Toast.makeText(this, "onBind()", Toast.LENGTH_SHORT).show();
42         Log.i(TAG, "onBind()");
43         mediaPlayer.start();
44         return null;
45     }
46 
47     @Override
48     public boolean onUnbind(Intent intent) {
49         Toast.makeText(this, "onUnbind()", Toast.LENGTH_SHORT).show();
50         Log.i(TAG, "onUnbind()");
51         mediaPlayer.stop();
52         return super.onUnbind(intent);
53     }
54 
55 }
2.给出主类MainActivity.java
MainActivity.java
 1 package com.cb.service;
 2 
 3 import android.app.Activity;
 4 import android.content.ComponentName;
 5 import android.content.Intent;
 6 import android.content.ServiceConnection;
 7 import android.os.Bundle;
 8 import android.os.IBinder;
 9 import android.util.Log;
10 import android.view.View;
11 import android.view.View.OnClickListener;
12 import android.widget.Button;
13 import android.widget.Toast;
14 
15 public class MainActivity extends Activity {
16     private Button mStartButton;
17     private Button mStopButton;
18     private Button mBindButton;
19     private Button mUnbindButton;
20 
21     // 设置日志工具标签
22     private String TAG = "MainActivity";
23 
24     @Override
25     public void onCreate(Bundle savedInstanceState) {
26         super.onCreate(savedInstanceState);
27         setContentView(R.layout.main);
28 
29         mStartButton = (Button) findViewById(R.id.startbutton);
30         mStopButton = (Button) findViewById(R.id.stopbutton);
31         mBindButton = (Button) findViewById(R.id.bindbutton);
32         mUnbindButton = (Button) findViewById(R.id.unbindbutton);
33 
34         /*
35          * ServiceConnection:当application与service建立连接后,
36          * serviceConnection将收到service启动或停止的消息
37          * ,通过serviceConnection中的onServiceConnected/ onServiceDisconnected进行处理.
38          */
39         final ServiceConnection conn = new ServiceConnection() {
40 
41             @Override
42             public void onServiceDisconnected(ComponentName name) {
43                 Toast.makeText(MainActivity.this, "onServiceDisconnected()",
44                         Toast.LENGTH_SHORT).show();
45                 Log.i(TAG, "onServiceDisconnected()");
46             }
47 
48             @Override
49             public void onServiceConnected(ComponentName name, IBinder service) {
50                 Toast.makeText(MainActivity.this, "onServiceConnected()",
51                         Toast.LENGTH_SHORT).show();
52                 Log.i(TAG, "onServiceConnected()");
53             }
54         };
55 
56         OnClickListener listener = new OnClickListener() {
57 
58             @Override
59             public void onClick(View v) {
60                 // TODO Auto-generated method stub
61                 Intent intent = new Intent(MainActivity.this,
62                         MusicService.class);
63 
64                 // 设置监听器
65                 switch (v.getId()) {
66                 case R.id.startbutton:
67                     startService(intent);
68                     break;
69 
70                 case R.id.stopbutton:
71                     stopService(intent);
72                     break;
73 
74                 case R.id.bindbutton:
75                     bindService(intent, conn, BIND_AUTO_CREATE);
76                     break;
77 
78                 case R.id.unbindbutton:
79                     unbindService(conn);
80                     break;
81                 }
82             }
83         };
84 
85         mStartButton.setOnClickListener(listener);
86         mStopButton.setOnClickListener(listener);
87         mBindButton.setOnClickListener(listener);
88         mUnbindButton.setOnClickListener(listener);
89 
90     }
91 
92     @Override
93     protected void onDestroy() {
94         super.onDestroy();
95         Toast.makeText(this, "onDestroy()", Toast.LENGTH_SHORT).show();
96         Log.i(TAG, "onDestroy()");
97     }
98 }

step4:图示




 

原文地址:https://www.cnblogs.com/chenbin7/p/2473554.html