关于 android service 和 thread
来源:互联网 发布:云计算怎么用 编辑:程序博客网 时间:2024/06/09 19:39
在安卓系统中,service是运行在主线程中的,而thread是用来创建子线程的。二者毫无关系! thread的运行时独立于activity的,当一个activity被销毁时,如果你没有主动停止 Thread 或者 Thread 里的 run 方法没有执行完毕的话,Thread 也会一直执行。当 Activity 被 finish 之后,你不再持有该 Thread 的引用。另一方面,你没有办法在不同的 Activity 中对同一 Thread 进行控制。 但是service却不同,当一个activity被销毁时,另外的activity还可以对service进行控制。因为任何 Activity 都可以控制同一 Service,而系统也只会创建一个对应 Service 的实例。因此可以把 Service 想象成一种消息服务,而你可以在任何有 Context 的地方调用 Context.startService、Context.stopService、 Context.bindService,Context.unbindService,来控制它,你也可以在 Service 里注册 BroadcastReceiver,在其他地方通过发送 broadcast 来控制它,当然这些都是 Thread 做不到的。
service
Service的生命周期方法比Activity少一些,只有onCreate, onStart(onStartCommand), onDestroy
我们有两种方式启动一个Service,他们对Service生命周期的影响是不一样的。
1.通过startService启动
Service会经历 onCreate --> onStart(onStartCommand)
stopService的时候直接onDestroy
如果是 调用者 直接退出而没有调用stopService的话,Service会一直在后台运行。
下次调用者再起来仍然可以stopService。
2.通过bindService启动
Service只会运行onCreate, 这个时候 调用者和Service绑定在一起
调用者退出了,Srevice就会调用onUnbind-->onDestroyed
所谓绑定在一起就共存亡了。
一个bindService启动的例子:
ServiceDemo.java
public class ServiceDemo extends Activity {Button btnBind, btnUnBind, btnGetServiceStatus;BindService bindService;LocalService localService;private boolean isBind = false;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);btnBind = (Button) findViewById(R.id.btnBind);btnUnBind = (Button) findViewById(R.id.btnUnBind);btnGetServiceStatus = (Button) findViewById(R.id.btnGetServiceStatus);OnClickListener listener = new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubswitch (v.getId()) {case R.id.btnBind:// Intent intent = new Intent();// // 隐式启动Service// intent.setAction("com.wang.servicedemo.BIND_SERVICE");// 显示启动ServiceIntent intent = new Intent(ServiceDemo.this,BindService.class);// 绑定指定的ServicebindService(intent, serviceConnection, BIND_AUTO_CREATE);isBind = true;break;case R.id.btnUnBind:if (isBind) {// 解除绑定Service,一般要是没有主动去解绑的话,可以在onDestory方法中解绑unbindService(serviceConnection);isBind = false;bindService = null;Toast.makeText(ServiceDemo.this,"--Service is Unbind.--", Toast.LENGTH_LONG).show();} else {Toast.makeText(ServiceDemo.this, "--你还未绑定Service--",Toast.LENGTH_LONG).show();}break;case R.id.btnGetServiceStatus:if (bindService == null) {Toast.makeText(ServiceDemo.this, "请先绑定Service",Toast.LENGTH_LONG).show();} else {Toast.makeText(ServiceDemo.this,"App name:" + bindService.getDemoName()+ "\n count:" + localService.getCount(),Toast.LENGTH_LONG).show();// localService.getService().MyMethod();}break;}}};btnBind.setOnClickListener(listener);btnGetServiceStatus.setOnClickListener(listener);btnUnBind.setOnClickListener(listener);}/** * 定义一个ServiceConnection对象, 实例化ServiceConnection接口的实现类, * 重写onServiceConnected()和onServiceDisconnected()方法 */private ServiceConnection serviceConnection = new ServiceConnection() {// 当Activity与Service通过非UnBind()方法断开连接的时候回调该方法@Overridepublic void onServiceDisconnected(ComponentName name) {bindService = null;Toast.makeText(ServiceDemo.this, "--Service UnConnected.--",Toast.LENGTH_LONG).show();}// 当Activity与Service连接成功的时候回调该方法@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {// 获取getService()方法返回的BindService对象localService = ((LocalService) service);bindService = localService.getService();bindService.MyMethod();Toast.makeText(ServiceDemo.this, "--Service Connected.--",Toast.LENGTH_LONG).show();System.out.println("--Service Connected.--");}};}
BindService.java
public class BindService extends Service {private int count = 0;private boolean isQuit = false;// 定义getService方法返回的对象public LocalService localService = new LocalService();/* * 创建Binder子类,Binder实现了IBinder接口, 这是一个内部类 */public class LocalService extends Binder {public int getCount() {return count;}public BindService getService() {return BindService.this;}}/* * Service子类必须实现的方法,绑定该Service时回调的方法; onbind方法只被调用一次,在第一个client或调用者 * 绑定至其的时候被调用。 返回的是Binder对象。 然后其他组件可以通过这个Binder 对象与该service 进行通讯。 */@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn localService;}/* * (non-Javadoc) 此方法只执行一次,当service再次被调用时,会执行onStartCommand方法 * * @see android.app.Service#onCreate() */@Overridepublic void onCreate() {// TODO Auto-generated method stubSystem.out.println("Service is Created.");// 创建并启动一个线程,动态修改count变量值new Thread() {@Overridepublic void run() {// TODO Auto-generated method stubwhile (!isQuit) {try {Thread.sleep(1000);// 使得当前线程休眠1000毫秒} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}count++;}}}.start();super.onCreate();}/* * (non-Javadoc)onStart方法已被onStartCommand方法代替,api不赞成使用 * * @see android.app.Service#onStart(android.content.Intent, int) */@Override@Deprecatedpublic void onStart(Intent intent, int startId) {// TODO Auto-generated method stubsuper.onStart(intent, startId);}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubreturn super.onStartCommand(intent, flags, startId);}// 在所有onUnbind被回调之后调用@Overridepublic void onDestroy() {// TODO Auto-generated method stubSystem.out.println("Service is Destroyed.");isQuit = true;super.onDestroy();}// 定义一个返回实例名的方法public String getDemoName() {return "Service实例";}// 在所有与Service绑定的客户端都解除绑定之后被回调@Overridepublic boolean onUnbind(Intent intent) {// TODO Auto-generated method stubSystem.out.println("Service is Unbind.");return true;// 表示下次客户端绑定的时候接受一个onRebind()的调用(而不是调用 onBind())}public void MyMethod() {for (int i = 0; i < 100; i++) {Log.i("44", "BindService-->MyMethod()");}}}
xml文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.wang.servicedemo.MainActivity" > <Button android:id="@+id/btnBind" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="绑定service" /> <Button android:id="@+id/btnGetServiceStatus" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="获得service状态" /> <Button android:id="@+id/btnUnBind" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="解绑service" /></LinearLayout>
最后在清单文件中声明service:
<service android:name="com.wang.servicedemo.BindService" > <intent-filter> <!-- 为该Service组件的intent-filter配置action ,用于隐式启动时使用--> <action android:name="com.wang.servicedemo.BIND_SERVICE" > </action> </intent-filter> </service>
- 关于 android service 和 thread
- Android Service和Thread区别
- 转android-Service和Thread的区别
- Android中Thread和Service的区别
- android-Service和Thread的区别
- android-Service和Thread的区别
- android-Service和Thread的区别
- android-Service和Thread的区别
- android-Service和Thread的区别
- [android基础]Service和Thread的区别
- android之Service和Thread的关系
- android-Service和Thread的区别
- Android中Service和Thread的区别
- android-Service和Thread的区别
- android中Service和Thread的区别
- android-Service和Thread的区别
- android中Service和Thread的区别
- Android Service和Thread的区别
- pat乙级1018
- handler机制
- pycharm默认快捷键:
- 蓝牙(BT04A、HC-05) 使用经验
- 7月份的经历+学习总结
- 关于 android service 和 thread
- python代码`if not x:` 和`if x is not None:`和`if not x is None:`使用
- 人生第一道cf的题
- 广播机制方式
- __int64与long long、long的区别
- PL\SQL 客户端配置 windows 64 ORACLE 提示:无法检测到对应的数据库名
- Python语法元素入门
- android 按钮倒计时读秒
- nginx 优化配置