最近在照着《第一行代码》这本书来学安卓,顺便记下笔记。主要的内容是Android中服务的第二种启动方式,通过活动绑定服务来启动服务,实现活动与服务之间的通信。

一. 首先创建一个服务类

 public class MyService extends Service{

     private DownloadBinder mBinder=new DownloadBinder();

     class DownloadBinder extends Binder{
public void startDownload(){
Log.d("MyService", "start download");
} public int getProgress(){
Log.d("MyService", "getProgress executed");
return 0;
}
} public IBinder onBind(Intent intent){
return mBinder;
} public void onCreate(){
super.onCreate();
Log.d("MyService", "onCreate executed");
} public int onStartCommand(Intent intent, int flags,int startId){
Log.d("MyService", "onStartCommand executed");
return super.onStartCommand(intent, flags, startId);
} public void onDestroy(){
Log.d("MyService", "onDestroy executed");
super.onDestroy();
}
}

在MyService里重写onCreate(), onStartCommand(), onDestroy()和onBind()方法,这里重点要说下的是onBind()方法,它会在服务被绑定时执行,并且返回一个实现了IBinder接口的实例。这里在MyService中新建了DownloadBinder继承Binder并将其作为onBind()方法的返回值。

二. 在活动的布局中加入两个按钮用于绑定服务和解除绑定服务

<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="com.example.servicetest.MainActivity" > <Button
android:id="@+id/bind_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Bind Service"/> <Button
android:id="@+id/unbind_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Unbind Service"/> </LinearLayout>

之后修改MainActicity中的代码

public class MainActivity extends Activity implements OnClickListener{

    private Button bindService;
private Button unbindService;
private MyService.DownloadBinder downloadBinder;
private ServiceConnection connection=new ServiceConnection() { @Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub } @Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
downloadBinder=(MyService.DownloadBinder)service;
downloadBinder.startDownload();
downloadBinder.getProgress();
}
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindService=(Button)findViewById(R.id.bind_service);
unbindService=(Button)findViewById(R.id.unbind_service);
bindService.setOnClickListener(this);
unbindService.setOnClickListener(this);
} //启动和停止服务
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {case R.id.bind_service:
Intent bindIntent=new Intent(this,MyService.class);
bindService(bindIntent, connection, BIND_AUTO_CREATE);
break;
case R.id.unbind_service:
unbindService(connection);
break;
default:
break;
}
} }

这里的要点:1. ServiceConnection类         2. Activity中的bindService和unbindService方法

自己的总结:Activity调用自己的bindService方法去绑定服务Service,这个方法里需要3个参数。既然是Activity和Service的绑定,那么这两个类的对象是一定要的,可以将这两个用一个Intent传入。还需要一个对象来代表两者之间的连接,所以第二个参数需要一个ServiceConnection的实例,这个类有两个方法:onServiceConnected和onServiceDisconnected分别在Activity绑定Service和接触绑定时执行。onServiceConnected(ComponentName name, IBinder service)这个方法里的第二个参数应该就是Service在绑定时执行onbind方法时返回的IBinder。

最后控制台的输出:

10月9日Android学习笔记:活动与服务之间的通信的更多相关文章

  1. 2015年10月22日CSS学习笔记

    XHTML1.0对HTML4.0的改进 借鉴了XML的写法,语法更加严格. 把页面的内容和样式分离了,废弃了html4中的表示样式的标签和属性.推荐使用css来描述页面的样式. CSS样式的优先级 ! ...

  2. 2016年3月16日Android学习笔记

    1.Jdk1.7以上switch语句中才能用字符串,在Android Studio中我改正了jdk的版本为1.8,但是还是出同样的错误,原来我用的sdk版本是4.4的,改成5的就没有问题了. 2.引入 ...

  3. 2016年3月17日Android学习笔记

    1.Java.io.ByteArrayOutputStream.writeTo()方法实例 java.io.ByteArrayOutputStream.writeTo(OutputStream out ...

  4. 2016年3月12日Android学习笔记

    1. //此句不能忘,否则onFling左右滑动不起作用 mLlExamView.setLongClickable(true); mLlExamView.setOnTouchListener(new ...

  5. SPSS 2019年10月24日 今日学习总结

    2019年10月24日今日课上内容1.SPSS掌握基于键值的一对多合并2.掌握重构数据3.掌握汇总功能 内容: 1.基于键值的一对多合并 合并文件 添加变量 合并方法:基于键值的一对多合并 变量 2. ...

  6. [2018-11-03]2018年10月28日宁波dotnet社区活动回顾及下次活动预告

    离上次活动,有半年了,汗.之后尽量保证每月一次,以组织为主,多邀请嘉宾来分享. 本次活动不足之处 人手不足:由于活动组织事项受限于人手(目前就我一个,这次活动前后我又应邀给大红鹰学院应届生介绍dotn ...

  7. 2016年3月1日Android实习笔记

    1:经查资料,Android中gif动画加载共有两种 1)利用WebView,WebView 主要调用三个方法:LoadUrl.LoadData.LoadDataWithBaseURL 2)主要用的是 ...

  8. 2016年3月11日Android学习日记

    1.调试技巧:当一次调试过后,可以在App重新返回当前的状态,然后再调试,而不用再点击Android studio的Debug按钮. 参考:http://www.2cto.com/kf/201506/ ...

  9. 2016年3月4日Android实习笔记

    1.让水平LinearLayout中的两个子元素分别居左和居右 在LinearLayout中有两个子元素,LinearLayout的orientation是horizontal.需要让第一个元素居左, ...

随机推荐

  1. 视觉中的深度学习方法CVPR 2012 Tutorial Deep Learning Methods for Vision

    Deep Learning Methods for Vision CVPR 2012 Tutorial  9:00am-5:30pm, Sunday June 17th, Ballroom D (Fu ...

  2. Datatable的查找和排序(Datatable.Select)

    Datatable  是一种常用的数据结构.数据类型有点类似于数据库中的表结构.在没有使用优秀的orm框架前,大部分的数据库的数据都是先变为Datatable 然后再通过代码转换变成 object. ...

  3. 夺命雷公狗-----React---2--组建

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  4. install sublime for linux

    Download Your Free eBooks NOW - 10 Free Linux eBooks for Administrators Python API, that available f ...

  5. 二叉查找树的Java实现

    为了克服对树结构编程的恐惧感,决心自己实现一遍二叉查找树,以便掌握关于树结构编程的一些技巧和方法.以下是基本思路: [1] 关于容器与封装.封装,是一种非常重要的系统设计思想:无论是面向过程的函数,还 ...

  6. CI框架多个表前缀,如何使用框架语句querybuilder

    最近用CI框架遇到一个问题.2个前提条件: 1.数据库设计不规范,有的有表前缀(如:ck_table1),有的没有(如:table2)或者表前缀不一样: 2.数据库操作又想使用数据库操作语句query ...

  7. php socket的一些问题

    在php手册看到了php socket的例子 但有些socket_read的循环判断有一些问题 造成进程的阻塞 实例是用phpsocket实现 客户端连接到socket server 发送文本 接受文 ...

  8. WIFI驱动的移植 realtek 8188

    一般我们拿到的android源代码中wifi应用层部分是好的, 主要是wifi芯片的驱动要移植并添加进去. wifi驱动的移植, 以realtek的8188etv为例到官网下载相应的驱动, 解压后可以 ...

  9. 结对编程—黄金点游戏WinForm单机版

    本小游戏场景来自邹欣老师的<移山之道>一书: "阿超的课都是下午两点钟,这时班上不少的同学都昏昏欲睡,为了让大家兴奋起来,阿超让同学玩一个叫"黄金点"的游戏: ...

  10. 2x2矩阵相乘模版

    由于Unity只有4x4矩阵,今天要做一个2x2矩阵的旋转,居然忘了顺序.故写下作为模版记录. 顺序: 下面是使用其进行旋转的C#代码: public struct Position { public ...