Android(java)学习笔记171:服务(service)之绑定服务调用服务里面的方法

1.绑定服务调用服务里面的方法,图解:

步骤:

(1)在Activity代码里面绑定 bindService(),以bind的方式开启服务 

                    bindServiceintent, new MyConn(), BIND_AUTO_CREATE);

参数intent:意图对象,服务对应的意图对象  new  Intent(this,Service.class)

参数ServiceConnection (接口,自定义其接口实现内部类MyConn() ):通讯频道,利用他可以获取服务成功绑定后得到的秘书

参数BIND_AUTO_CREATE:常量,服务不存在会自动创建

(2)实现MyConn接口实现内部类

/**
     * 服务连接成功的通讯频道
     *
     */
    private class MyConn implements ServiceConnection{
        //当服务被成功连接的时候调用的方法
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            重要参数IBinder,代表的就是中间人,服务的秘书
        }
        //当服务失去连接的时候调用的方法
        @Override
       public void onServiceDisconnected(ComponentName name) {
            
        }
    }

(3)如果服务被成功绑定  会执行onBind的方法       

public  IBinder onBind (Intent  intent )

这个方法的返回值为 IBinder 就是服务内部的秘书

(4)扩展实现服务内部的秘书,可以间接的调用服务的方法

      /**
     * 服务内部的秘书,可以调用服务的方法
     *
     */
    public class MyBinder extends Binder{
        /**
         * 调用服务的方法。
         * @param money 钱
         */
        public void callMethodInService(int money){
            if(money>500){
                methodInService();
            }else{
                Toast.makeText(DemoService.this, "这点钱还想办事呀?", 0).show();
            }
        }
    }

(5)在MyConn成功绑定的时候,就得到了IBInder对象, MyBinder

(6)利用MyBinder间接调用服务的方法

2.案例代码:

(1)布局文件activity_main.xml

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:orientation="vertical"
 6     tools:context=".MainActivity" >
 7 
 8     <Button
 9         android:layout_width="match_parent"
10         android:layout_height="wrap_content"
11         android:onClick="bind"
12         android:text="绑定服务" />
13 
14     <Button
15         android:layout_width="match_parent"
16         android:layout_height="wrap_content"
17         android:onClick="unbind"
18         android:text="解除绑定服务" />
19 
20     <Button
21         android:layout_width="match_parent"
22         android:layout_height="wrap_content"
23         android:onClick="call"
24         android:text="调用服务里面的方法" />
25 
26 </LinearLayout>

布局效果如下:

(2)MainActivity.java

 1 package com.itheima.bind;
 2 
 3 import com.itheima.bind.DemoService.MyBinder;
 4 
 5 import android.app.Activity;
 6 import android.content.ComponentName;
 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 
13 public class MainActivity extends Activity {
14     MyBinder myBinder;
15 
16     @Override
17     protected void onCreate(Bundle savedInstanceState) {
18         super.onCreate(savedInstanceState);
19         setContentView(R.layout.activity_main);
20     }
21     
22     protected void onDestory(Bundle savedInstanceState) {
23         super.onDestory();
24         ----;//解绑服务
25     }
26 
27     /**
28      * 绑定服务,获取服务里面的秘书,间接的调用服务里面的方法。
29      * @param view
30      */
31     public void bind(View view){
32         Intent intent = new Intent(this,DemoService.class);
33         //intent 意图
34         //conn 服务的通讯频道
35         //1 服务如果在绑定的时候不存在,会自动创建
36         System.out.println("1.采用bind的方式开启服务");
37         bindService(intent, new MyConn(), BIND_AUTO_CREATE);
38     }
39     
40     
41     /**
42      * 解绑服务
43      * @param view
44      */
45     public void unbind(View view){
46        
47         System.out.println("解绑服务");
48         if(myBinder != null) {
49             unbindService(new MyConn());
50             myBinder = null;
51         }
52    
53     }
54     /**
55      * 服务连接成功的通讯频道
56      *
57      */
58     private class MyConn implements ServiceConnection{
59         //当服务被成功连接的时候调用的方法
60         @Override
61         public void onServiceConnected(ComponentName name, IBinder service) {
62             System.out.println("3. 得到了服务的一个连接,通讯频道,获取到服务内部的秘书");
63             myBinder = (MyBinder) service;
64             System.out.println("4.把ibinder强制类型转化成秘书MyBinder");
65         }
66         //当服务失去连接的时候调用的方法
67         @Override
68         public void onServiceDisconnected(ComponentName name) {
69             
70         }
71     }
72     
73     /**
74      * 调用服务里面的方法。
75      * @param view
76      */
77     public void call(View view){
78         System.out.println("5.利用mybinder间接的调用服务的方法");
79         myBinder.callMethodInService(3000);
80     }
81 }

其中创建的服务DemoService.java如下:

 1 package com.itheima.bind;
 2 
 3 import android.app.Service;
 4 import android.content.Intent;
 5 import android.os.Binder;
 6 import android.os.IBinder;
 7 import android.widget.Toast;
 8 
 9 public class DemoService extends Service {
10 
11     /**
12      * 在服务被绑定的时候调用的方法
13      * 
14      * IBinder 服务内部的秘书
15      */
16     @Override
17     public IBinder onBind(Intent intent) {
18         System.out.println("2. 服务如果成功绑定会执行onbind,返回服务内部的秘书 mybinder");
19         return new MyBinder();
20     }
21     /**
22      * 服务内部的秘书,可以调用服务的方法
23      *
24      */
25     public class MyBinder extends Binder{
26         /**
27          * 调用服务的方法。
28          * @param money 钱
29          */
30         public void callMethodInService(int money){
31             if(money>500){
32                 methodInService();
33             }else{
34                 Toast.makeText(DemoService.this, "这点钱还想办事呀?", 0).show();
35             }
36         }
37     }
38     
39     
40 
41     /**
42      * 服务里面的方法
43      */
44     public void methodInService(){
45         Toast.makeText(this, "哈哈,我是服务的方法,被你调用了。", 0).show();
46     }
47     
48     @Override
49     public void onCreate() {
50         System.out.println("服务被创建了");
51         super.onCreate();
52     }
53     @Override
54     public void onDestroy() {
55         System.out.println("服务被销毁了。");
56         super.onDestroy();
57     }
58 }

这里定义一个Service,当然要在AndroidMainfest.xml文件中注册一下:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 3     package="com.itheima.bind"
 4     android:versionCode="1"
 5     android:versionName="1.0" >
 6 
 7     <uses-sdk
 8         android:minSdkVersion="8"
 9         android:targetSdkVersion="17" />
10 
11     <application
12         android:allowBackup="true"
13         android:icon="@drawable/ic_launcher"
14         android:label="@string/app_name"
15         android:theme="@style/AppTheme" >
16         <activity
17             android:name="com.itheima.bind.MainActivity"
18             android:label="@string/app_name" >
19             <intent-filter>
20                 <action android:name="android.intent.action.MAIN" />
21 
22                 <category android:name="android.intent.category.LAUNCHER" />
23             </intent-filter>
24         </activity>
25         <service android:name="com.itheima.bind.DemoService"></service>
26     </application>
27 
28 </manifest>

3. 绑定服务的应用场景

 提供一个服务,后台运行,里面有一些公共的逻辑供调用.

>1. 微信支付, 微信有一个支付的服务,绑定,调用支付的方法
>2. sony手机,人脸识别的服务,绑定到这个服务传递一个照片就会把人脸标记出来
>3. 音乐播放器,后台服务里面播放音乐绑定服务暂停下一曲上一曲

原文地址:https://www.cnblogs.com/hebao0514/p/4800175.html