Service与Activity的差别在于:Service一直在后台执行,他没实用户界面,绝不会到前台来。

一,创建和配置Service

开发Service须要两个步骤:1。继承Service子类,2。在Manifest.xml文件里配置Service

Service中的方法:

public class FirstService extends Service
{
// 必须实现的方法。返回一个IBinder对象,应用程序可通过该对象与Service组件通信
@Override
public IBinder onBind(Intent arg0)
{
return null;
}
// Service被创建时回调该方法。
@Override
public void onCreate()
{
super.onCreate();
System.out.println("Service is Created");
}
// Service被启动时回调该方法
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
System.out.println("Service is Started");
return START_STICKY;
}
// Service被关闭之前回调。
@Override
public void onDestroy()
{
super.onDestroy();
System.out.println("Service is Destroyed");
}
}

Manifest.xml中配置service

<!-- 配置一个Service组件 -->
<service android:name=".FirstService">
<intent-filter>
<!-- 为该Service组件的intent-filter配置action -->
<action android:name="org.service.FIRST_SERVICE" />
</intent-filter>
</service>

二,启动和停止Service

1,startService 启动的服务:主要用于启动一个服务执行后台任务,不进行通信。訪问者与Service没有关联。即使訪问者退出了。Service仍然执行。停止服务使用stopService

bindService 启动的服务:该方法启动的服务要进行通信。停止服务使用unbindService

public class StartServiceTest extends Activity
{
Button start, stop; @Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 获取程序界面中的start、stop两个button
start = (Button) findViewById(R.id.start);
stop = (Button) findViewById(R.id.stop);
// 创建启动Service的Intent
final Intent intent = new Intent();
// 为Intent设置Action属性
intent.setAction("org.service.FIRST_SERVICE");
start.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
// 启动指定Serivce
startService(intent);
}
});
stop.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
// 停止指定Serivce
stopService(intent);
}
});
}

2,绑定本地Service并与之通信

假设訪问者和Service之间须要进行方法调用或者数据传递,则应该使用bindService和unbindService方法启动关闭Service

boolean bindService(Intent service, ServiceConnection conn,int flags)方法:

service:这个參数通过Intent指定要启动的Service

conn:ServiceConnection 对象。该对象用于监听訪问者与Service之间的连接情况。

当訪问者与Service之间连接成功时将会回调ServiceConnection对象的onServiceConnected(ComponentName
name, IBinder service);当Service所在的宿主中止。导致Service与訪问者之间断开时会回调ServiceConnection对象的onServiceDisconnected(ComponentName name)方法

flags:绑定时是否自己主动创建Service。0或BIND_AUTO_CREATE

ServiceConnection对象的onServiceConnected方法中有一个IBinder对象。该对象就可以与被绑定Service之间的通信

通信原理:当开发Service是。

该Service类必须提供一个IBinder onBind(Intent intent)方法,在绑定本地Service的情况下,onBind(Intent
intent)方法所返回的IBinder对象会传给ServiceConnection对象的onServiceConnected的(ComponentName
name, IBinder service)的service參数。这样訪问者就可使用该IBinder对象与Service进行通信了

BindService.java

public class BindService extends Service//继承Service
{
private int count;
private boolean quit;
// 定义onBinder方法所返回的对象。此binder会传给訪问者
private MyBinder binder = new MyBinder();
// 通过继承Binder来实现IBinder类
public class MyBinder extends Binder //①
{
public int getCount()
{
// 获取Service的执行状态:count
return count;
}
}
// 必须实现的方法。绑定该Service时回调该方法
@Override
public IBinder onBind(Intent intent)
{
System.out.println("Service is Binded");
// 返回IBinder对象
return binder;
}
// Service被创建时回调该方法。 @Override
public void onCreate()
{
super.onCreate();
System.out.println("Service is Created");
// 启动一条线程、动态地改动count状态值
new Thread()
{
@Override
public void run()
{
while (!quit)
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
}
count++;
}
}
}.start();
}
// Service被断开连接时回调该方法
@Override
public boolean onUnbind(Intent intent)
{
System.out.println("Service is Unbinded");
return true;
}
// Service被关闭之前回调该方法。
@Override
public void onDestroy()
{
super.onDestroy();
this.quit = true;
System.out.println("Service is Destroyed");
}
}

配置Service组件:

<!-- 配置一个Service组件 -->
<service android:name=".BindService">
<intent-filter>
<!-- 为该Service组件的intent-filter配置action -->
<action android:name="org.crazyit.service.BIND_SERVICE" />
</intent-filter>
</service>

BindServiceTest.java

public class BindServiceTest extends Activity
{
Button bind, unbind, getServiceStatus;
// 保持所启动的Service的IBinder对象
BindService.MyBinder binder;
// 定义一个ServiceConnection对象
private ServiceConnection conn = new ServiceConnection()
{
// 当该Activity与Service连接成功时回调该方法
@Override
public void onServiceConnected(ComponentName name
, IBinder service)
{
System.out.println("--Service Connected--");
// 获取Service的onBind方法所返回的MyBinder对象
binder = (BindService.MyBinder) service; //①
} // 当该Activity与Service断开连接时回调该方法
@Override
public void onServiceDisconnected(ComponentName name)
{
System.out.println("--Service Disconnected--");
}
}; @Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 获取程序界面中的start、stop、getServiceStatusbutton
bind = (Button) findViewById(R.id.bind);
unbind = (Button) findViewById(R.id.unbind);
getServiceStatus = (Button) findViewById(R.id.getServiceStatus);
// 创建启动Service的Intent
final Intent intent = new Intent();
// 为Intent设置Action属性
intent.setAction("org.crazyit.service.BIND_SERVICE");
bind.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View source)
{
// 绑定指定Serivce
bindService(intent, conn, Service.BIND_AUTO_CREATE);
}
});
unbind.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View source)
{
// 解除绑定Serivce
unbindService(conn);
}
});
getServiceStatus.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View source)
{
// 获取、并显示Service的count值
Toast.makeText(BindServiceTest.this,
"Serivce的count值为:" + binder.getCount(),
Toast.LENGTH_SHORT).show(); //②
}
});
}
}

Android中的Service组件具体解释的更多相关文章

  1. Android中Broadcast Receiver组件具体解释

    BroadcastReceiver(广播接收器)是Android中的四大组件之中的一个. 以下是Android Doc中关于BroadcastReceiver的概述: ①广播接收器是一个专注于接收广播 ...

  2. 【Android中Broadcast Receiver组件具体解释 】

    BroadcastReceiver(广播接收器)是Android中的四大组件之中的一个. 以下是Android Doc中关于BroadcastReceiver的概述: ①广播接收器是一个专注于接收广播 ...

  3. Android 中的 Service 全面总结(转载)

    转载地址:http://www.cnblogs.com/newcj/archive/2011/05/30/2061370.html 感谢作者 Android 中的 Service 全面总结 1.Ser ...

  4. 详解Android中的四大组件之一:Activity详解

    activity的生命周期 activity的四种状态 running:正在运行,处于活动状态,用户可以点击屏幕,是将activity处于栈顶的状态. paused:暂停,处于失去焦点的时候,处于pa ...

  5. (转载)Android中的Service:Binder,Messenger,AIDL(2)

    前言 前面一篇博文介绍了关于Service的一些基本知识,包括service是什么,怎么创建一个service,创建了一个service之后如何启动它等等.在这一篇博文里有一些需要前一篇铺垫的东西,建 ...

  6. (转载)所有分类 > 开发语言与工具 > 移动开发 > Android开发 Android中的Service:默默的奉献者 (1)

    前言 这段时间在看一些IPC相关的东西,这里面就不可避免的要涉及到service,进程线程这些知识点,而且在研究的过程中我惊觉自己对这些东西的记忆已经开始有些模糊了——这可要不得.于是我就干脆花了点心 ...

  7. android中的Serveice组件

    创建 配置 Service: 1.定义一个继承了Service类的子类 2.在 AndroidManifest.xml清单文件中对开发的Service进行配置 Service和Activity很相似, ...

  8. Android中的Service详解

    今天我们就来介绍一下Android中的四大组件中的服务Service,说到Service, 它分为本地服务和远程服务:区分这两种服务就是看客户端和服务端是否在同一个进程中,本地服务是在同一进程中的,远 ...

  9. android中使用spinner组件,以key,value的方式

    接着上一篇文章的内容:android中使用spinner组件 稍做修改,以key,value的方式,在实际使用中,经常需要获取的值并不一定跟显示的内容一致. 需要先添加一个对象类,用来描述key,va ...

随机推荐

  1. mysql管理和基本操作

    进去mysql:mysql –uroot –p 重启数据库:[root@nanaLinux ~]# /etc/init.d/mysqld restart 1.Mysql忘记root密码 // 查看my ...

  2. hdu6086(AC 自动机)

    hdu6086 题意 字符串只由 \(01\) 组成,求长度为 \(2L\) 且包含给定的 \(n\) 个子串的字符串的个数(且要求字符串满足 \(s[i] \neq s[|s| - i + 1]\) ...

  3. 最小生成树Kruskal+LCA+bfs【bzoj4242】水壶

    Description JOI 君所居住的 IOI 市以一年四季都十分炎热著称. IOI 市被分成 \(H\) 行,每行包含 \(W\) 块区域.每个区域都是建筑物.原野.墙壁之一. IOI 市有 \ ...

  4. numeric column can contains null

  5. 微信小程序开发教程(四)线程架构与开发步骤

    线程架构 从前面的章节我们可以知道,.js文件是页面逻辑处理层.我们可以按需在app.js和page.js中添加程序在生命周期的每个阶段相应的事件.如在页面的onLoad时进行数据的下载,onShow ...

  6. [APIO2015]巴厘岛的雕塑

    题目描述 印尼巴厘岛的公路上有许多的雕塑,我们来关注它的一条主干道. 在这条主干道上一共有 NN 座雕塑,为方便起见,我们把这些雕塑从 11 到 NN 连续地进行标号,其中第 ii 座雕塑的年龄是 Y ...

  7. 【莫队算法】【权值分块】bzoj3339 Rmq Problem

    如题. #include<cstdio> #include<algorithm> #include<cmath> using namespace std; #def ...

  8. Dom4jDemo应用-保存手机信息

    ---恢复内容开始--- import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStr ...

  9. 线程协作-CountDownLatch

    CountDownLatch允许一个或多个线程等待其他线程完成操作.

  10. nodeJs常用API

    1.url (1)url.parse返回url对象的各种参数 url.parse(url,true/false,true/false);//默认url.parse(url,false,false); ...