android四大组件之Service.docx
《android四大组件之Service.docx》由会员分享,可在线阅读,更多相关《android四大组件之Service.docx(21页珍藏版)》请在冰点文库上搜索。
android四大组件之Service
android四大组件之Service
Service是一个可以在后台执行长时间运行操作而不提供用户界面的应用组件。
服务可由其他应用组件启动,而且即使用户切换到其他应用,服务仍将在后台继续运行。
此外,组件可以绑定到服务,以与之进行交互,甚至是执行进程间通信(IPC)。
作者:
i_seek_u来源:
segmentfault|2016-12-0909:
23
收藏
分享
最近因为还没找到工作所以也趁着现在有时间,将以前的只是整理下,要不然总容易遗忘,今天就来讲解下Service的用法。
作为Android的四大组件之一,其重要性可想而知。
在应用中我们主要是用来进行一些后台操作,不需与应用UI进行交互,执行耗时任务等。
官方文档中这样说:
Service是一个可以在后台执行长时间运行操作而不提供用户界面的应用组件。
服务可由其他应用组件启动,而且即使用户切换到其他应用,服务仍将在后台继续运行。
此外,组件可以绑定到服务,以与之进行交互,甚至是执行进程间通信(IPC)。
例如,服务可以处理网络事务、播放音乐,执行文件I/O
或与内容提供程序交互,而所有这一切均可在后台进行。
Service的用途:
1.在后台执行耗时操作,但不需要与用户进行交互。
2.一个应用暴露出来的一些供其他应用使用的功能。
这里需要声明一点,Service是运行在主线程中,因而如果需要进行耗时操作或者访问网络等操作,需要在Service中再开启一个线程来执行(使用IntentService的话则不需要在自己手动开启线程)。
启动Service
启动一个Service有两种方式:
1.Context.startService()
1.Context.bindService()
(图片截取自官方文档:
...)
startService()方式启动Service,我们启动之后是没有办法再对Service进行控制的,而且启动之后该Service是一直在后台运行的,即使它里面的一些代码执行完毕,我们要想终止该Service,就需要在他的代码里面调用stopSelf()方法或者直接调用stopService()方法。
而通过bindService()方法启动的Service,客户端将获得一个到Service的持久连接,客户端会获取到一个由Service的onBind(Intent)方法返回来的IBinder对象,用来供客户端回调Service中的回调方法。
我们无论使用那种方法,都需要定义一个类,让它继承Service类,并重写其中的几个方法,如果我们是采用startService()方式启动的话,只需要重写onCreate()、onStartCommand(Intentintent,intflags,intstartId)、onDestroy()方法即可(其实我们也可以重写),而如果采用的是bindService()方法启动的话,我们就需要重写onCreate()、onBind(Intentintent)、onUnbind(Intentintent)方法.注意,作为四大组件之一,Service使用之前要在清单文件中进行配置。
1.
2. ......
3. 4. android:
name=".MyService">
5.
6.
Context.startService()
MyService.java的代码:
1.public class MyService extends Service {
2. public MyService() {
3. }
4.
5. @Override
6. public void onCreate() {
7. super.onCreate();
8.
9. Log.i("test","onCrete executed !
");
10. }
11.
12. @Override
13. public int onStartCommand(Intent intent, int flags, int startId) {
14.
15. Log.i("test","onStartComand executed !
");
16. return super.onStartCommand(intent, flags, startId);
17. }
18.
19. @Override
20. public void onDestroy() {
21. super.onDestroy();
22. Log.i("test","onDestroy executed !
");
23. }
24.}
MainActivity.java的代码如下:
1.public class MainActivity extends AppCompatActivity implements View.OnClickListener{
2.
3. Button btnStart,btnStop;
4. @Override
5. protected void onCreate(Bundle savedInstanceState) {
6. super.onCreate(savedInstanceState);
7. setContentView(R.layout.activity_main);
8.
9. btnStart = (Button) findViewById(R.id.btn_start);
10. btnStop = (Button) findViewById(R.id.btn_stop);
11. btnStart.setOnClickListener(this);
12. btnStop.setOnClickListener(this);
13. }
14.
15.
16. @Override
17. public void onClick(View view) {
18.
19. Intent mIntent = new Intent(MainActivity.this,MyService.class);
20.
21. switch (view.getId()){
22. case R.id.btn_start:
23. startService(mIntent);
24. break;
25. case R.id.btn_stop:
26. stopService(mIntent);
27. break;
28. }
29. }
30.}
主界面就两个按钮,一个用来启动Service,一个用来停止Service:
下面我们先点击START按钮,Log信息如下:
可以看出,onCreate()方法先执行,然后onStartCommand()方法紧接着执行,那么如果我们再次点击启动按钮呢?
结果如下图:
我们可以看到,这次onCreate()方法没有再执行,而是直接执行了onStartCommand()方法,这是因为Service只在第一次创建的时候才执行onCreate()方法,如果已经创建了,那之后再次调用startService()启动该Service的时候,只会去执行onStartCommand()方法方法,而不会再执行onCreate()方法。
接下来我们点击停止按钮,可以看到,onDestroy()方法被执行了:
注意,如果我们不点击停止按钮手动停止该Service的话,该Service会一直在后台运行,即使它的onStartCommand()方法中的代码已经执行完毕,在下图中我们可以看到:
这时候我们的这个Service是一直在后台执行的,即使它的onStartCommand()方法中的代码已经执行完了。
如果我们想要它自动停止的话,可以将onStartCommand()方法中的代码修改如下:
1.@Override
2. public int onStartCommand(Intent intent, int flags, int startId) {
3.
4. Log.i("test","onStartComand() executed !
");
5. stopSelf();
6. return super.onStartCommand(intent, flags, startId);
7. }
Context.bindService()
采用该方法的代码就稍微比以前的多了,因为我们需要在客户端对Service进行控制,因而会在MainActivity中创建一个匿名内部类ServiceConnection,然后会在bindService()方法和unbindService()方法中将其传入。
MyService.java中的代码如下:
1.public class MyService extends Service {
2. private MyBinder myBinder = new MyBinder();
3.
4. public MyService() {
5. }
6.
7. @Override
8. public void onCreate() {
9. super.onCreate();
10. Log.i("test","onCreate() executed !
");
11. }
12.
13. @Override
14. public void onDestroy() {
15. super.onDestroy();
16. Log.i("test","onDestroy() executed !
");
17. }
18.
19. @Override
20. public boolean onUnbind(Intent intent) {
21.
22. Log.i("test","onUnbind executed !
");
23. return super.onUnbind(intent);
24. }
25.
26. @Override
27. public IBinder onBind(Intent intent) {
28. Log.i("test","onBind() executed !
");
29. return myBinder;
30. }
31.
32. class MyBinder extends Binder{
33. public void startDownload(){
34.
35. Log.i("test", "MyBinder中的startDownload() executed !
");
36. // 执行具体的下载任务,需开启一个子线程,在其中执行具体代码
37. }
38. }
39.}
MainActivity.java的代码如下:
1.public class MainActivity extends AppCompatActivity implements View.OnClickListener{
2.
3. Button btnBind,btnUnBind;
4. MyService.MyBinder myBinder ;
5. @Override
6. protected void onCreate(Bundle savedInstanceState) {
7. super.onCreate(savedInstanceState);
8. setContentView(R.layout.activity_main);
9.
10. btnBind = (Button) findViewById(R.id.bind);
11. btnUnBind = (Button) findViewById(R.id.btn_unBind);
12. btnBind.setOnClickListener(this);
13. btnUnBind.setOnClickListener(this);
14.
15. }
16.
17. ServiceConnection mServiceConnection = new ServiceConnection() {
18. @Override
19. public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
20. // 将IBinder向下转型为我们的内部类MyBinder
21. myBinder = (MyService.MyBinder) iBinder;
22. // 执行下载任务
23. myBinder.startDownload();
24. }
25.
26. @Override
27. public void onServiceDisconnected(ComponentName componentName) {
28.
29. }
30. };
31.
32. @Override
33. public void onClick(View view) {
34.
35. Intent mIntent = new Intent(MainActivity.this,MyService.class);
36.
37. switch (view.getId()){
38. case R.id.bind:
39. // 绑定Service
40. bindService(mIntent,mServiceConnection,BIND_AUTO_CREATE);
41. break;
42. case R.id.btn_unBind:
43. // 取消绑定Service
44. unbindService(mServiceConnection);
45. break;
46. }
47. }
48.}
点击绑定按钮;
点击取消绑定按钮:
注意,如果我们没有先点击绑定,而是直接点击的取消绑定,程序会直接crash,报以下错误:
1.java.lang.IllegalArgumentException:
Service not registered:
com.qc.admin.myserializableparceabledemo.MainActivity$1@8860e28
2. at android.app.LoadedApk.forgetServiceDispatcher(LoadedApk.java:
1120)
3. at android.app.ContextImpl.unbindService(ContextImpl.java:
1494)
4. at android.content.ContextWrapper.unbindService(ContextWrapper.java:
616)
5. at com.qc.admin.myserializableparceabledemo.MainActivity.onClick(MainActivity.java:
71)
细心的你也许早就发现了,Log中并没有打印"onServiceDisconnectedexecuted!
"这句,也就是说没有调用onServiceDisconnected()方法?
从字面理解,onServiceConnected()方法是在Service建立连接的时候调用的,onServiceDisconnected()不就应该是在Service断开连接的时候调用的吗?
其实不然,我们查看该方法的文档就知道了:
CalledwhenaconnectiontotheServicehasbeenlost.Thistypicallyhappenswhentheprocesshostingtheservicehascrashedorbeenkilled.ThisdoesnotremovetheServiceConnectionitself--thisbindingtotheservicewillremainactive,andyouwillreceiveacalltoonServiceConnected(ComponentName,IBinder)whentheServiceisnextrunning.
意思就是:
当绑定到该Service的连接丢失的时候,该方法会被调用,典型的情况就是持有该Service的进程crash掉了,或者被杀死了。
但是这并不会移除ServiceConnection自身--它仍然是保持活跃状态,当Service下次被执行的时候,onServiceConnected(ComponentName,IBinder)方法仍然会被调用。
但是要注意,如果我们按照刚才说的,不是先点击bindService()方法,而是直接点击unbindService()方法,程序虽然也是crash掉了,但onServiceDisconnected()方法并不会被调用,这个很容易理解,毕竟都没有建立连接呢,谈何断开连接啊。
但是如果我们已经绑定了Service,然后在后台直接终止该Service呢?
结果会怎样?
答案是onServiceDisconnected()方法仍然不会调用。
这里我觉得应该是只有在意外的情况下进程结束,是由系统自动调用的,而非我们手动停止的。
我们可以查看该方法内部的注释:
Thisiscalledwhentheconnectionwiththeservicehasbeen
unexpectedlydisconnected--thatis,itsprocesscrashed.Becauseit
isrunninginoursameprocess,weshouldneverseethishappen.
这段文字清楚的说明了该方法执行的场景:
异常情况下导致断开了连接。
也就是进程crash掉了。
因为它运行在我们应用程序所在的进程中,因而我们将永远不希望看到这种情况发生。
Context.startService()和Context.bindService()同时使用
这两种方式是可以同时使用的,但是要注意,startService()和stopService()方法是对应的,而bindService()和unBind()方法是对应的,也就是说如果我们先调用startService()之后调用bindService()方法,或者相反,那么我们如果只调用stopService()或者只调用bindService()都无法停止该Service,只有同时调用才可以。
下面来看下具体代码:
MainActivity.java
1.public class MainActivity extends AppCompatActivity implements View.OnClickListener{
2.
3. Button btnStart,btnStop,btnBind,btnUnBind;
4. MyService.MyBinder myBinder ;
5. @Override
6. protected void onCreate(Bundle savedInstanceState) {
7. super.onCreate(savedInstanceState);
8. setContentView(R.layout.activity_main);
9.
10. btnStart = (Button) findViewById(R.id.btn_start);
11. btnStop = (Button) findViewById(R.id.btn_stop);
12. btnBind = (Button) findViewById(R.id.btn_bind);
13. btnUnBind = (Button) findViewById(R.id.btn_unBind);
14.
15. btnStart.setOnClickListener(this);
16. btnStop.setOnClickListener(this);
17. btnBind.setOnClickListener(this);