android Service(startService bindService)详解以及全面总结
2017-04-11 11:29
549 查看
1.Service基本概念
Service是Android中四大组件之一,是一个没有用户界面的在后台运行执行耗时操作的应用组件。其他应用组件能够启动Service,并且当用户切换到另外的应用场景,Service将持续在后台运行。另外,一个组件能够绑定到一个service与之交互(IPC机制),例如,一个service可能会处理网络操作,播放音乐,操作文件I/O或者与内容提供者(content provider)交互,所有这些活动都是在后台进行。
那么,什么时候,我们需要使用service呢?
我们知道,service是运行在后台的应用,对于用户来说失去了被关注的焦点。这就跟我们打开了音乐播放之后,便想去看看图片,这时候我们还不想音乐停止,这里就会用到service;又例如,我们打开了一个下载链接之后,我们肯定不想瞪着眼睛等他下载完再去做别的事情,对吧?这时候如果我们想手机一边在后台下载,一边可以让我去看看新闻啥的,就要用到service。
Service有两种状态,“启动的”和“绑定”。
2.Service生命周期
Service也有自己的生命周期,前面我们使用到的onCreate,onStartCommand,onBind和onDestroy等方法都是在服务的生命周期内可能回调的方法。
一旦在项目的任何位置调用了Context的startService(intent)方法,相应的服务就会启动起来,并回调onStartCommand。如果 这个服务之前还没创建过,onCreate()方法会先于onStartCommand()方法执行。
服务启动了之后一直保持运行状态,直到stopService(intent)或stopSelf()方法被调用。
注意虽然每调用一次startService()方法,onStartCommand()就会执行一次,但实际上每个服务都只会存在一个实例。所以不管你调用了多少次startService(intent)方法,只需调用一次stopService()或stopSelf()方法,服务就会停止下来了。
另外,还可以调用Context的bindService()来获取一个服务的持久连接,这时就会回调服务中的onBind()方法。类似地,如果这个服务之前还没有创建过,onCreate()方法会先于onBind()方法执行。之后,调用方可以获取到onBind()方法里返回的IBinder对象的实例,这样就能自由地和服务进行通信了。只要调用方和服务之间的连接没有断开,服务就会一直保持运行状态。
当调用了startService()方法后,又去调用stopService()方法,这时服务中的onDestroy()方法就会执行,表示服务已经销毁了。类似地,当调用了bindService()方法后,又去调用unbindService()方法,onDestroy()方法也会执行,这两种情况都很好理解。但是需要注意,我们是完全有可能对一个服务既调用了startService()方法,又调用了bindService()方法的,这种情况下该如何才能让服务销毁掉?
根据android系统的机制,一个服务只要被启动或者绑定了之后就会一直处于运行状态,必须要让以上两种条件同时不满足,服务才能被销毁。所以,这种情况下需要同时调用stopService()和unbindService()方法,onDestroy()方法才会执行。
3.案例
ServiceDemo
Manifest
大小: 112 KB
查看图片附件
Service是Android中四大组件之一,是一个没有用户界面的在后台运行执行耗时操作的应用组件。其他应用组件能够启动Service,并且当用户切换到另外的应用场景,Service将持续在后台运行。另外,一个组件能够绑定到一个service与之交互(IPC机制),例如,一个service可能会处理网络操作,播放音乐,操作文件I/O或者与内容提供者(content provider)交互,所有这些活动都是在后台进行。
那么,什么时候,我们需要使用service呢?
我们知道,service是运行在后台的应用,对于用户来说失去了被关注的焦点。这就跟我们打开了音乐播放之后,便想去看看图片,这时候我们还不想音乐停止,这里就会用到service;又例如,我们打开了一个下载链接之后,我们肯定不想瞪着眼睛等他下载完再去做别的事情,对吧?这时候如果我们想手机一边在后台下载,一边可以让我去看看新闻啥的,就要用到service。
Service有两种状态,“启动的”和“绑定”。
2.Service生命周期
Service也有自己的生命周期,前面我们使用到的onCreate,onStartCommand,onBind和onDestroy等方法都是在服务的生命周期内可能回调的方法。
一旦在项目的任何位置调用了Context的startService(intent)方法,相应的服务就会启动起来,并回调onStartCommand。如果 这个服务之前还没创建过,onCreate()方法会先于onStartCommand()方法执行。
服务启动了之后一直保持运行状态,直到stopService(intent)或stopSelf()方法被调用。
注意虽然每调用一次startService()方法,onStartCommand()就会执行一次,但实际上每个服务都只会存在一个实例。所以不管你调用了多少次startService(intent)方法,只需调用一次stopService()或stopSelf()方法,服务就会停止下来了。
另外,还可以调用Context的bindService()来获取一个服务的持久连接,这时就会回调服务中的onBind()方法。类似地,如果这个服务之前还没有创建过,onCreate()方法会先于onBind()方法执行。之后,调用方可以获取到onBind()方法里返回的IBinder对象的实例,这样就能自由地和服务进行通信了。只要调用方和服务之间的连接没有断开,服务就会一直保持运行状态。
当调用了startService()方法后,又去调用stopService()方法,这时服务中的onDestroy()方法就会执行,表示服务已经销毁了。类似地,当调用了bindService()方法后,又去调用unbindService()方法,onDestroy()方法也会执行,这两种情况都很好理解。但是需要注意,我们是完全有可能对一个服务既调用了startService()方法,又调用了bindService()方法的,这种情况下该如何才能让服务销毁掉?
根据android系统的机制,一个服务只要被启动或者绑定了之后就会一直处于运行状态,必须要让以上两种条件同时不满足,服务才能被销毁。所以,这种情况下需要同时调用stopService()和unbindService()方法,onDestroy()方法才会执行。
3.案例
ServiceDemo
package com.test.service; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; public class ServiceDemo extends Service { private int progress ; //开启线程动态的修改progress private Thread thread = new Thread(){ @Override public void run() { while(progress < 10){ progress++; try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); break ; } } } }; public class MessageBinder extends Binder{ //用于activity使用 public int getProgress() { return progress; } } @Override public IBinder onBind(Intent intent) { System.out.println("service 已绑定"); thread.start(); return new MessageBinder(); } @Override public void onCreate() { System.out.println("service 已创建"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { System.out.println("service已启动"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); System.out.println("service停止"); } @Override public boolean onUnbind(Intent intent) { System.out.println("service解除绑定"); thread.interrupt(); return super.onUnbind(intent); } }
package com.test.activity; import android.app.Activity; import android.app.Service; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import com.test.R; import com.test.service.ServiceDemo; public class ServiceActivity extends Activity { private Button startServiceButton; private Button stopServiceButton; private Button bindServiceButton; private Button unbindServiceButton; private Button getServiceValueButton; private static TextView textView; private static ProgressBar progressBar; // 判断service是否启动 private boolean isServiceStarted = false ; int progress; // Activity和Service通信的桥梁 private ServiceDemo.MessageBinder binder; private static Handler handler = new Handler() { @Override public void handleMessage(Message msg) { textView.setText("Service中获取的值:" + msg.arg1); progressBar.setProgress(msg.arg1); } }; // 用于得到binder对象 private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { System.out.println("Service 连接"); binder = (ServiceDemo.MessageBinder) service; } @Override public void onServiceDisconnected(ComponentName name) { System.out.println("Service 断开连接"); } }; private final Thread thread = new Thread() { @Override public void run() { System.out.println("线程已启动"); Message message = null; while ((progress = binder.getProgress()) <= 10) { message = handler.obtainMessage(); message.arg1 = progress; message.sendToTarget(); try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("线程已终止"); break; } //跳出线程 if(progress == 10){ break ; } } unbindService(connection); isServiceStarted = false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.service); startServiceButton = (Button) findViewById(R.id.startService); stopServiceButton = (Button) findViewById(R.id.stopService); bindServiceButton = (Button) findViewById(R.id.bindService); unbindServiceButton = (Button) findViewById(R.id.unbindService); getServiceValueButton = (Button) findViewById(R.id.getServiceValue); textView = (TextView) findViewById(R.id.serviceText); progressBar = (ProgressBar) findViewById(R.id.progressBar); final Intent intent = new Intent(); intent.setAction("COM.TEST.SERVICE.SERVICEDEMO"); // 开启service startServiceButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startService(intent); } }); // 停止service stopServiceButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { stopService(intent); } }); // 绑定service bindServiceButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(!isServiceStarted){ isServiceStarted = true; bindServiceButton.setClickable(false); bindService(intent, connection, Service.BIND_AUTO_CREATE); } } }); // 解除绑定service unbindServiceButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!thread.isInterrupted()) { thread.interrupt(); } if (isServiceStarted) { unbindService(connection); isServiceStarted = false; } bindServiceButton.setClickable(true); } }); // 获取service内容 getServiceValueButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { System.out.println(thread.isInterrupted()); if (!thread.isInterrupted()) { thread.start(); } } }); } }
Manifest
<service android:name=".service.ServiceDemo" android:exported="false" > <intent-filter> <action android:name="COM.TEST.SERVICE.SERVICEDEMO" /> </intent-filter> </service>
大小: 112 KB
查看图片附件
相关文章推荐
- 【Android四大组件之Service】(二)Android中Service的使用详解和注意点(LocalService),及startService与bindService的区别
- Android 中的 Service 全面总结详解【下】
- 混合使用startService,bindService,以及tartForegroud方法使用总结
- Android 服务之startService和bindService以及前台服务的创建
- Android 中的 Service 全面总结详解【上】
- 混合使用startService,bindService,以及tartForegroud方法使用总结
- 混合使用startService,bindService,以及tartForegroud方法使用总结
- Android学习札记三:初涉Service(1)之Context.startService()与Context.bindService()区别
- Android里Service的bindService()和startService()混合使用深入分析
- Android 中的 Service 全面总结 .
- Android 中的 Service 全面总结
- Android 中的 Service 全面总结(一)
- Android 四大组件之(2)Service实现原理以及AIDL语言的使用详解
- Android 中的 Service 全面总结
- Android Service之 startService与bindService
- android 开发StartService 和BindService
- Android Service全面总结
- Android 中的 Service 全面总结
- Android 中的 Service 全面总结
- Android 中的 Service 全面总结