最近在照着《第一行代码》这本书来学安卓,顺便记下笔记。主要的内容是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. dubbo源码分析1-reference bean创建

    dubbo源码分析1-reference bean创建 dubbo源码分析2-reference bean发起服务方法调用 dubbo源码分析3-service bean的创建与发布 dubbo源码分 ...

  2. mysql安装配置问题(linux下)

    1.安装后使用:mysql -u root -p 无法登录mysql 错误提示:ERROR 1045 (28000): Access denied for user 'root'@'localhost ...

  3. R数据实战vehicles--1

    新建项目vehicles-project 数据文件vehicles.csv与varlabels.txt放在项目文件中

  4. git设置hooks 钩子

    github是可以设置hooks的,看:在设置webhooks & services,可在Just the push event.是设定向你的服务器发请求,然后再做相应的处理. https:/ ...

  5. [转]JAVA程序执行顺序,你了解了吗:JAVA中执行顺序,JAVA中赋值顺序

    本文主要介绍以下两块内容的执行顺序,熟悉的大虾可以直接飘过. 一.JAVA中执行顺序 静态块 块 构造器 父类构造器 二.JAVA中赋值顺序 静态块直接赋值 块直接赋值 父类继承的属性已赋值 静态变量 ...

  6. [Ubuntu] Profile error when launching google-chrome

    Whenever I launch google-chrome, a window is displayed which contains this message: Your profile cou ...

  7. 解决redmine写操作很慢的问题

    以前刚开始时用redmine是直接使用它的webrick服务器来运行的,后来为了提高性能,采用nginx+passenger的方式来驱动redmine,访问速度快了不少,但是在新建问题或更新问题时变得 ...

  8. Hibernate 一对多 保存和修改数据

    Student和Sclass表,Student外键cid是Sclass的cid create table sclass( cid ) primary key, cname ) )go create t ...

  9. JQuery EasyUI的datagrid的使用方式总结

    JQuery EasyUI的datagrid的使用方式总结第一步:添加样式和js脚本在前台添加展示数据表格的table元素 例如: <div> <table id="tt& ...

  10. s3c2440 移值u-boot-2016.03 第2篇 支持Nand flash启动

    1, 要求:在4K 的代码以内,完成 NOR NAND 类型判断,初始化 NAND 复制自身到 SDRAM ,重定向. 2, 在 /arch/arm/cpu/arm920t/ 文件夹里 添加一个 in ...