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:

 <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"
tools:context=".MainActivity" > <Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="bind"
android:text="绑定服务" /> <Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="unbind"
android:text="解除绑定服务" /> <Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="call"
android:text="调用服务里面的方法" /> </LinearLayout>

布局效果如下:

(2)MainActivity.java:

 package com.itheima.bind;

 import com.itheima.bind.DemoService.MyBinder;

 import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View; public class MainActivity extends Activity {
MyBinder myBinder; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
} protected void onDestory(Bundle savedInstanceState) {
super.onDestory();
----;//解绑服务
} /**
* 绑定服务,获取服务里面的秘书,间接的调用服务里面的方法。
* @param view
*/
public void bind(View view){
Intent intent = new Intent(this,DemoService.class);
//intent 意图
//conn 服务的通讯频道
//1 服务如果在绑定的时候不存在,会自动创建
System.out.println("1.采用bind的方式开启服务");
bindService(intent, new MyConn(), BIND_AUTO_CREATE);
} /**
* 解绑服务
* @param view
*/
public void unbind(View view){ System.out.println("解绑服务");
if(myBinder != null) {
unbindService(new MyConn());
myBinder = null;
} }
/**
* 服务连接成功的通讯频道
*
*/
private class MyConn implements ServiceConnection{
//当服务被成功连接的时候调用的方法
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
System.out.println("3. 得到了服务的一个连接,通讯频道,获取到服务内部的秘书");
myBinder = (MyBinder) service;
System.out.println("4.把ibinder强制类型转化成秘书MyBinder");
}
//当服务失去连接的时候调用的方法
@Override
public void onServiceDisconnected(ComponentName name) { }
} /**
* 调用服务里面的方法。
* @param view
*/
public void call(View view){
System.out.println("5.利用mybinder间接的调用服务的方法");
myBinder.callMethodInService(3000);
}
}

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

 package com.itheima.bind;

 import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast; public class DemoService extends Service { /**
* 在服务被绑定的时候调用的方法
*
* IBinder 服务内部的秘书
*/
@Override
public IBinder onBind(Intent intent) {
System.out.println("2. 服务如果成功绑定会执行onbind,返回服务内部的秘书 mybinder");
return new MyBinder();
}
/**
* 服务内部的秘书,可以调用服务的方法
*
*/
public class MyBinder extends Binder{
/**
* 调用服务的方法。
* @param money 钱
*/
public void callMethodInService(int money){
if(money>500){
methodInService();
}else{
Toast.makeText(DemoService.this, "这点钱还想办事呀?", 0).show();
}
}
} /**
* 服务里面的方法
*/
public void methodInService(){
Toast.makeText(this, "哈哈,我是服务的方法,被你调用了。", 0).show();
} @Override
public void onCreate() {
System.out.println("服务被创建了");
super.onCreate();
}
@Override
public void onDestroy() {
System.out.println("服务被销毁了。");
super.onDestroy();
}
}

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

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.itheima.bind"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" /> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.itheima.bind.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.itheima.bind.DemoService"></service>
</application> </manifest>

3. 绑定服务的应用场景

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

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

Android(java)学习笔记171:服务(service)之绑定服务调用服务里面的方法的更多相关文章

  1. Android(java)学习笔记171:Service生命周期

    1.Service的生命周期         Android中的Service(服务)与Activity不同,它是不能和用户交互,不能自己启动的,运行在后台的程序,如果我们退出应用的时候,Servic ...

  2. Android:日常学习笔记(7)———探究UI开发(1)

    Android:日常学习笔记(7)———探究UI开发(1) 常用控件的使用方法 TextView 说明:TextView是安卓中最为简单的一个控件,常用来在界面上显示一段文本信息. 代码: <T ...

  3. 《Java学习笔记(第8版)》学习指导

    <Java学习笔记(第8版)>学习指导 目录 图书简况 学习指导 第一章 Java平台概论 第二章 从JDK到IDE 第三章 基础语法 第四章 认识对象 第五章 对象封装 第六章 继承与多 ...

  4. Java学习笔记4

    Java学习笔记4 1. JDK.JRE和JVM分别是什么,区别是什么? 答: ①.JDK 是整个Java的核心,包括了Java运行环境.Java工具和Java基础类库. ②.JRE(Java Run ...

  5. 20155234 2016-2017-2第十周《Java学习笔记》学习总结

    20155234第十周<Java学习笔记>学习总结 教材学习内容总结 网络编程 在两个或两个以上的设备(例如计算机)之间传输数据.程序员所作的事情就是把数据发送到指定的位置,或者接收到指定 ...

  6. Android:日常学习笔记(2)——分析第一个Android应用程序

    Android:日常学习笔记(2)——分析第一个Android应用程序 Android项目结构 整体目录结构分析 说明: 除了APP目录外,其他目录都是自动生成的.APP目录的下的内容才是我们的工作重 ...

  7. java学习笔记之基础篇

    java选择语句之switch   //switch可以用于等值判断 switch (e) //int ,或则可以自动转化成int 的类型,(byte char short)枚举jdk 7中可以防止字 ...

  8. Android Studio 学习笔记(一)环境搭建、文件目录等相关说明

    Android Studio 学习笔记(一)环境搭建.文件目录等相关说明 引入 对APP开发而言,Android和iOS是两大主流开发平台,其中区别在于 Android用java语言,用Android ...

  9. Java web与web gis学习笔记(二)——百度地图API调用

    系列链接: Java web与web gis学习笔记(一)--Tomcat环境搭建 Java web与web gis学习笔记(二)--百度地图API调用 JavaWeb和WebGIS学习笔记(三)-- ...

  10. 0028 Java学习笔记-面向对象-Lambda表达式

    匿名内部类与Lambda表达式示例 下面代码来源于:0027 Java学习笔记-面向对象-(非静态.静态.局部.匿名)内部类 package testpack; public class Test1{ ...

随机推荐

  1. [Selenium] 使用Chrome Driver 的示例

    //导入Selenium 库和 ChromeDriver 库 pachage com.learningselenium.simplewebdriver; import java.util.concur ...

  2. 【转】IntelliJ IDEA2017.3激活

    原文地址:https://blog.csdn.net/qq_27686779/article/details/78870816 http://idea.java.sx/ 简单快捷!! ———————— ...

  3. java io流中怎么在一个文本中追加字符串

    1/ FileOutputStream(File file, boolean append)2/FileWriter(File file, boolean append) 不管哪一种IO都有 appe ...

  4. Hibernate 4.3 配置文件实现

    1.建立web项目 2.复制相关的jar文件到 项目的lib目录下antlr-2.7.7.jardom4j-1.6.1.jarhibernate-commons-annotations-4.0.5.F ...

  5. iOS [CIContext initWithOptions:]: unrecognized selector sent to instance 模拟器 iOS 8.4

    在模拟器(iPhone 4s,iOS 8.4)中运行应用时, 应用crash在了使用CIContext(options:nil) 这个API的一个纯Swift第三方库. StackOverFlow的解 ...

  6. iOS UITextView 设置圆角边框线

    textView.layer.borderColor = UIColor.lightGray.cgColor textView.layer.cornerRadius = 4 textView.laye ...

  7. SpringBoot 整合SpringMVC 原理探究

    https://blog.csdn.net/cml_blog/article/details/70196572 Spring Web MVC 的配置 Bean :WebMvcProperties

  8. Codeforces 1108F(克鲁斯卡尔的理解)

    最小生成树会多样的情况是:两个或多个边等长且连通同样的两个并查集块. 所以可以跑一遍克鲁斯卡尔,每次把当前等长的边数出来,注意不要边找边并查,因为有一部分边是正常跑生成树我们也不会要他的,这种直接跳了 ...

  9. UVA - 1658 Admiral

    3. C - Admiral 题意:给定v(3<=v<=1000)个节点,e(3<=e<=10000)条边的又向加权图,求1->v的两条不相交的路径,使得权和最小. 思路 ...

  10. pyton 基础,运算符及字符类型。

    一.python运算符: 二.数据类型: 1.数字: int  :整型 32位机器上一个整数取值范围为-2**31~2**31-1即-2147483648~2147483647 64位机器上一个整数取 ...