一 什么是Service

  Service作为安卓四大组件之一,拥有重要的地位。Service和Activity级别相同,只是没有界面,是运行于后台的服务。这个运行“后台”是指不可见,不是指在后台线程中,事实上四大组件都是运行在UI线程中,都不能在各自的生命周期方法中执行耗时操作或者网络请求。

二 如何使用Service

  Service主要可以分为两类:Local Service、Remote Service。这里以比较常用的Local Service为例,介绍Service的两种使用方法。

  (1)通过Context.startService()启动Service,通过Context.stopService()结束服务。

  新建一个MyService类继承Service,重写onCreate()、onStartCommand()、onDestroy()方法,然后在MainActivity中设置两个按钮,增加其各自点击事件用于启动和停止MyService。

package com.example.haisun.myapplication3;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log; /**
* Created by HaiSun on 2015/10/10.
*/
public class MyService extends Service { @Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
} @Override
public void onCreate() {
super.onCreate();
Log.d("MyService","onCreate executed");
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyService","onStartCommand executed");
// new Thread(new Runnable() {
// @Override
// public void run() {
// //具体逻辑
// stopSelf();
// }
// }).start();
return super.onStartCommand(intent, flags, startId);
} @Override
public void onDestroy() {
Log.d("MyService","onDestroy executed");
super.onDestroy();
}
}
package com.example.haisun.myapplication3;

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;
import android.widget.Button; public class MainActivity extends Activity implements View.OnClickListener{ @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button start = (Button)findViewById(R.id.start_service);
Button stop = (Button)findViewById(R.id.stop_service);
start.setOnClickListener(this);
stop.setOnClickListener(this); } @Override
public void onClick(View v) {
switch (v.getId()){
case R.id.start_service:
Intent intent = new Intent(this,MyService.class);
startService(intent);
break;
case R.id.stop_service:
Intent stopIntent = new Intent(this,MyService.class);
stopService(stopIntent);
break; default:
break; } } }

  (2)通过Context.bindService()来绑定一个service,通过Context.unbindService()解绑。

  这里只是在上面的例子上增加了一些内容即可。

  1.在MyService里面新建一个内部类DownBinder继承Binder

class DownLoadBinder extends Binder {
public void startDownLoad(){
Log.d("MyService","startDownLoad executed");
}
public int getProgress(){
Log.d("MyService","getProgress executed");
return 0;
}

  2.通过MyService中的onBind方法返回DownBinder的实例,供Activity绑定成功后的回调

private DownLoadBinder mBinder = new DownLoadBinder();

    @Override
public IBinder onBind(Intent intent) {
return mBinder;
}

  3.Activity中绑定,需要新建一个ServiceConnection对象,获得回调的Binder,进而得到DownBinder实例

private MyService.DownLoadBinder downLoadBinder;

    private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downLoadBinder = (MyService.DownLoadBinder)service;
downLoadBinder.startDownLoad();
downLoadBinder.getProgress();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};

  4.类似的,设置两个按钮,增加绑定和解绑的点击事件

    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;

三 Service的生命周期

  下图为Google官方提供的配图

  

附:完整的Demo地址:https://github.com/sunhai1992/ServiceTest

Service学习笔记的更多相关文章

  1. Web Service学习笔记:动态调用WebService

    原文:Web Service学习笔记:动态调用WebService 多数时候我们通过 "添加 Web 引用..." 创建客户端代理类的方式调用WebService,但在某些情况下我 ...

  2. Web Service学习笔记(webservice、soap、wsdl、jws详细分析)

    Web Service概述 Web Service的定义 W3C组织对其的定义如下,它是一个软件系统,为了支持跨网络的机器间相互操作交互而设计.Web Service服务通常被定义为一组模块化的API ...

  3. Web Service学习笔记

    Web Service概述 Web Service的定义 W3C组织对其的定义如下,它是一个软件系统,为了支持跨网络的机器间相互操作交互而设计.Web Service服务通常被定义为一组模块化的API ...

  4. Web Service学习笔记(webservice、soap、wsdl、jws详细分析) (转)

    Web Service概述 Web Service的定义 W3C组织对其的定义如下,它是一个软件系统,为了支持跨网络的机器间相互操作交互而设计.Web Service服务通常被定义为一组模块化的API ...

  5. Linux daemon与service 学习笔记

    service 常驻在内存中的进程,且可以提供一些系统或网络功能,就是服务.   daemon service的提供需要进程的运行,所以实现service的程序我们称为daemon.   eg: 实现 ...

  6. Java Web Service 学习笔记

    一.服务端 1. 创建Java工程 2. 创建接口HostipalServiceInterface package ws_server; import javax.jws.WebMethod; imp ...

  7. Dynamic CRM 2013学习笔记(二十五)JS调用web service 实现多条记录复制(克隆)功能

    前面介绍过如何克隆一条当前的记录: Dynamic CRM 2013学习笔记(十四)复制/克隆记录 , 主要是通过界面上加一个字段,单击form上的clone 按钮时,改变这个字段的值以触发插件来实现 ...

  8. Dynamic CRM 2013学习笔记(二十九)报表设计:reporting service 报表开发常见问题

    在报表开发过程中,经常会遇到各种各样的问题,比如The report cannot be displayed. (rsProcessingAborted),一点有意义的提示都没有:再就是分页问题,经常 ...

  9. Android(java)学习笔记227:服务(service)之服务的生命周期 与 两种启动服务的区别

    1.之前我们在Android(java)学习笔记171:Service生命周期 (2015-08-18 10:56)说明过,可以回头看看: 2.Service 的两种启动方法和区别: (1)Servi ...

随机推荐

  1. Android startActivityForResult 回传数据

    一个activity打开新的activity,新的activity关闭之后,返回数据.原来的activity要接收返回的数据,在开启新的activity时,就需要调用startActivityForR ...

  2. 第二百八十三节,MySQL数据库-MySQL存储过程

    MySQL数据库-MySQL存储过程 MySQL存储过程,也就是有点像MySQL函数,但是他与MySQL函数是有区别的,后面会讲到函数,所以注意区分 注意:函数与存储过程的区别 存储过程是:CREAT ...

  3. e640. 使一个组件可拖动

    This example demonstrates the code needed to make a component draggable. The object being transferre ...

  4. js 动态设置 option 的selected 选项

    思路:通过for循环判断每个选项,一旦满足条件则设置其selected属性为true即可,关键代码: var obj = document.getElementById(select_id); for ...

  5. jquery-插入兄弟元素

    1.after方法 在匹配元素集合中的每个元素的 后面 插入参数所指定的内容,作为其兄弟节点 参数类型说明: 1)普通字符串(可包含各种html标签) $('div').after('html字符串' ...

  6. .NETFramework、C#、VisualStudio 这三者之间关系,你了解吗!

    .NetFrameWork 是微软开发的以"虚拟机"运行,以通用语言运行库为基础,在其上面进行各种语言开发的一个开发平台. C# 是一个和平台更好交互,以托管在虚拟机上的一个语法糖 ...

  7. laravel 5.3 多用户认证

    不知道对不对,乱来一下!!!! 1)laravel自带了一个用户认证系统,要使用的话,直接运行一下命令就可以用了 php artisan make:auth 会生成相应的控制器.路由和模版文件 2)数 ...

  8. 数组内Merge

    数组al[0...mid-1]和al[mid...num-1]两个部分都已经分别排好序.要求合并使得整个数组al有序.请给出合并merge的代码.要求空间复杂度为O(1). /* 数组a[begin, ...

  9. PL/SQL编程1-基础

    编写第一个存储过程 create or replace procedure test_pro1 is begin ','zydev'); end; / 查看错误 show error 执行存储过程 e ...

  10. Hessain 方法重载

     在相应的配置文件里面加上这句话. <property name="overloadEnable" value="true"></proper ...