`

Android之Service学习篇二:Service启动方式之boundService

 
阅读更多

转于:

http://blog.csdn.net/wulianghuan/article/details/8600361

------------------------------------------------------------------------------

 

上一篇中介绍了Service的第一种方式,startService,这一篇来讲解一下另一张方式 bindService。

当创建一个能提供绑定功能的服务时,我们必须提供一个IBinder对象,客户端能使用这个对象与服务进行交换。在Android中有三种定义方式:

1、扩展Binder类 (条件:服务和应用在同一个进程当中,是最常见的情况)

2、使用Messager

3、使用AIDL (Android Interface Defination Language)

 

 

Bound Services

 

A bound service is the server in a client-server interface. A bound service allows components (such as activities) to bind to the service, send requests, receive responses, and even perform interprocess communication (IPC). A bound service typically lives only while it serves another application component and does not run in the background indefinitely.

 

这里以扩展Binder类为例讲解如何创建Bound Services.

 

Binder

extends Object
implements IBinder
java.lang.Object
   ↳ android.os.Binder

很明显,Binder实现了IBinder这接口。

 

通过扩展Binder类创建Bound Service的步骤如下:

a、在Service类中,创建一个Binder实例,包含客户端能调用的公共方法,返回当前服务对象;

b、在onBind()方法中返回Binder实例;

c、在客户端,从onServiceConnected方法中获得Binder实例。

 

工程目录结构:


运行界面:


源代码:

MainActivity.java:

 

  1. package com.service.activity;  
  2.   
  3. import com.service.activity.BinderService.MyBinder;  
  4. import android.app.Activity;  
  5. import android.content.ComponentName;  
  6. import android.content.Context;  
  7. import android.content.Intent;  
  8. import android.content.ServiceConnection;  
  9. import android.os.Bundle;  
  10. import android.os.IBinder;  
  11. import android.view.View;  
  12. import android.view.View.OnClickListener;  
  13. import android.widget.Button;  
  14.   
  15. public class MainActivity extends Activity {  
  16.     private Button btnStartService;  
  17.     private Button btnstopService;  
  18.     private boolean isConnected = false;  
  19.     @Override  
  20.     public void onCreate(Bundle savedInstanceState) {  
  21.         super.onCreate(savedInstanceState);  
  22.         setContentView(R.layout.main);  
  23.         btnStartService = (Button)findViewById(R.id.btnStartService);  
  24.         btnStartService.setOnClickListener(listener);  
  25.         btnstopService = (Button)findViewById(R.id.btnStopService);  
  26.         btnstopService.setOnClickListener(listener);  
  27.     }  
  28.       
  29.     private OnClickListener listener = new OnClickListener() {  
  30.           
  31.         @Override  
  32.         public void onClick(View v) {  
  33.             switch (v.getId()) {  
  34.             case R.id.btnStartService:  
  35.                 funBindService();  
  36.                 break;  
  37.             case R.id.btnStopService:  
  38.                 funUnBindService();  
  39.                 break;  
  40.             default:  
  41.                 break;  
  42.             }  
  43.         }  
  44.         private void funBindService() {  
  45.             Intent intent = new Intent(MainActivity.this, BinderService.class);  
  46.             bindService(intent, conn, Context.BIND_AUTO_CREATE);  
  47.         }  
  48.   
  49.         private void funUnBindService() {  
  50.             if(isConnected == true){  
  51.                 unbindService(conn);  
  52.             }  
  53.         }  
  54.           
  55.     };  
  56.       
  57.     private ServiceConnection conn = new ServiceConnection() {  
  58.           
  59.         @Override  
  60.         public void onServiceDisconnected(ComponentName name) {  
  61.             isConnected = false;  
  62.         }  
  63.         //与Service连接时被回调  
  64.         @Override  
  65.         public void onServiceConnected(ComponentName name, IBinder iBinder) {  
  66.             MyBinder myBinder = (MyBinder)iBinder;  
  67.             BinderService service = myBinder.getService();  
  68.             service.MyMethod();  
  69.             isConnected = true;  
  70.         }  
  71.     };  
  72. }  


BinderService.java

 

  1. package com.service.activity;  
  2.   
  3. import android.app.Service;  
  4. import android.content.Intent;  
  5. import android.os.Binder;  
  6. import android.os.IBinder;  
  7. import android.util.Log;  
  8.   
  9. public class BinderService extends Service{  
  10.     private static final String TAG = "BinderService";  
  11.     private MyBinder myBinder = new MyBinder();  
  12.     //内部类,扩展自Binder类  
  13.     public class MyBinder extends Binder{  
  14.         public BinderService getService(){  
  15.             return BinderService.this;  
  16.         }  
  17.     }  
  18.     //复写onBind方法,并且返回IBinder的实现类  
  19.     @Override  
  20.     public IBinder onBind(Intent intent) {  
  21.         Log.i(TAG, "onBind");  
  22.         return myBinder;  
  23.     }  
  24.       
  25.     public void MyMethod(){  
  26.         Log.i(TAG, "MyMethod");  
  27.     }  
  28.   
  29.     @Override  
  30.     public boolean onUnbind(Intent intent) {  
  31.         Log.i(TAG, "onUnbind");  
  32.         return super.onUnbind(intent);  
  33.     }  
  34.       
  35.     @Override  
  36.     public void onDestroy() {  
  37.         Log.i(TAG, "onDestroy");  
  38.         super.onDestroy();  
  39.     }  
  40.       
  41. }  



 

 


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.     <Button   
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="启动service"  
  11.         android:id="@+id/btnStartService"/>  
  12.     <Button   
  13.         android:layout_width="wrap_content"  
  14.         android:layout_height="wrap_content"  
  15.         android:text="停止service"  
  16.         android:id="@+id/btnStopService"/>  
  17.   
  18. </LinearLayout>  


点击启动service,日志输出信息:

 

点击停止service,日志输出信息:


 

分享到:
评论

相关推荐

    Android Service之bound实现

    Android Service之bound实现

    Android Service简单实例

    关于Android Service的简单实例:属于start service类型,而不是bound service。

    浅谈Android中Service的注册方式及使用

    Service通常总是称之为“后台服务”,其中“后台”一词是相对于前台而言的,具体是指其...一般而言,从Service的启动方式上,可以将Service分为Started Service和Bound Service。无论哪种具体的Service启动类型,都是通

    绑定服务BoundService详解之AIDL的使用(自定义属性也包含其中)

    代码比较简单,但是步骤结合博客还是很详细的,可以看我的博客http://blog.csdn.net/superbiglw/article/details/53156177

    android的服务

    让我们来看下如何创建Service: 创建一个Service Android中已经定义了一个 ‘Service’类,所有其他的Service都继承于该类。Service类中定义了一系列的生命周期相关的方法,如: onCreate(), onStart(), onDestroy()...

    Android 开发指南(二) 服务绑定

    Android 开发指南(二) 服务绑定 Bound Service

    kotlin-foregroundService:具有android o通知的前台服务android的Kotlin代码

    kotlin-foregroundService 具有android o通知的前台服务android的Kotlin代码 MainActivity.kt class MainActivity : AppCompatActivity() { var myService: MyService... service: IBinder) { val binder = servic

    Android学习笔记之Service

    一个Service是App的一个组件,没有任何的UI,可以长时间的在后台无限期运行。可以在主线程之外的单独的线程中执行,也可以在应用程序组件(如活动)中进行管理。例如音乐播放器,可以让音乐在后台进行播放。 Service的...

    Asynchronous Android Programming

    "Asynchronous Android Programming" English | ISBN: 1785883240 | 2016 | 394 pages About This Book Construct scalable and performant applications to take advantage of multi-thread asynchronous ...

    Android Studio 3.2 Development Essentials, Kotlin Edition

    Android Studio 3.2 Development Essentials – Kotlin Edition 版本: Developing Android 9 Apps Using Android Studio 3.2, Kotlin and Android Jetpack By 作者: Neil Smyth ISBN-10 书号: 0960010939 ISBN-13 ...

    RabbitMQ for Android

    A connection is set up and the queue is bound to group ids. MainActivity starts a service in background which handles the connection with the server. I'm using `EventBus` to communicate between ...

    Asynchronous Android Programming(PACKT,2ed,2016)

    Asynchronous programming has acquired immense importance in Android programming, especially when we want to make use of the number of independent processing units (cores) available on the most recent ...

    TimedDog:适用于Android应用的超时库

    我已经停止使用WorkManager并迁移到Bound Service 。样本修改您的应用程序类,或者创建一个不存在的应用程序类,并在onCreate()方法中初始化TimedDog 。 class MyApp extends Application { @Override public ...

    Android服务应用ClockService实现闹钟功能

    实验步骤:使用BoundService方式开启服务 1、首先定义布局文件,这里不做过多赘述 3、 定义一个Service服务类,然后在类里面定义一个MyBinder的内部类,用于获取Service对象与Service对象状态。在内部类中必须要...

    lee_location_background

    bound_service 颤振中的绑定服务。 入门 这是Flutter中绑定服务的简单实现。 这基于 。 绑定服务使您可以在Flutter应用程序内部运行后台代码,即使该应用程序使用服务的绑定和解除绑定也可以打开或关闭该应用程序...

    OLA_Play_Music_App:音乐流应用程序

    服务(意向服务,绑定服务) OAuth-(Google登录)(FireBase) 自定义RecyclerView适配器SQLite数据库休息电话(排球,翻新) 图像渲染(滑行) JSON解析(Moshi) 内隐,明确意图Android 6.0运行时权限查看活页夹...

Global site tag (gtag.js) - Google Analytics