一、定义

  运行在后台,没有页面,不可见。优先级高于Activity,当系统内存不足时,会先释放一些Activity。注意,Service同样是运行在主线程中,不能做一些耗时操作。如果一定要做一些耗时的操作,启动一个新的线程,在新的线程中来处理。

二、用途:

  播放音乐,记录地理位置的改变,监听某些动作。

三、Sevice分类:

  1、本地服务(Local Service):是一种本地服务,一般用于应用程序内部,通过startService方法启动,通过stopService,stopSelf,stopSelfResult方法停止。另一种服务器启动方式:bindService,unbindService。

  2、远程服务(Remote Service):Android内部多个应用程序之间。定义Ibinder接口,暴露数据。

  

四、Service声明周期:

  Service声明周期分为两种情况:

  1、通过startService方式启动的服务,为左边方式,onCreate-->onStartCommand-->service Running -->stopXXZXOnDestroy;

  特点:启动后服务和启动源没有任何联系,无法得到服务对象。

  2、通过bind方式启动服务,为右边所示方式,OnCreate--> onBind--> Clients are bound to service --> onUnbind -->onDestroy;

  特点:通过Ibinder接口实例,返回一个ServiceConnection对象给启动源。通过ServiceConnection对象的相关方法可以得到Service对象。

示例:

1、start方式声明周期示例

AndroidManifest.xml,首先在配置文件中注册服务,添加服务名称

<service android:name="MyService1"></service>

MyService1.java,创建服务类,继承Service抽象方法,实现onCreate,onStartCommand,onDestroy,onBind方法,

package com.example.servicedemo;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder; public class MyService1 extends Service{
@Override //服务创建方法,只启动一次
public void onCreate() {
System.out.println("onCreate");
super.onCreate();
} @Override //服务启动方法
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("StartCommand");
return super.onStartCommand(intent, flags, startId);
} @Override //服务销毁方法
public void onDestroy() {
System.out.println("Destroy");
super.onDestroy();
} @Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
} }

main.xml,页面中添加两个按钮startService和stopService。

<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"> <TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start:" /> <Button
android:onClick="doClick"
android:id="@+id/btn_start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="StartService" /> <Button
android:onClick="doClick"
android:id="@+id/btn_stop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="StopService" /> </LinearLayout>

main.java,后台代码

package com.example.servicedemo;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View; public class MainActivity extends Activity {
Intent intent; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
} public void doClick(View v) {
switch (v.getId()) {
case R.id.btn_start:
//创建intent对象
intent = new Intent(MainActivity.this,MyService1.class);
//启动一个服务
startService(intent);
break;
case R.id.btn_stop:
//结束一个服务
stopService(intent);
break;
}
} }

  onCreate方法只是第一次被调用,只调用一次,除非Service对象被卸载了,onStartCommand点击一次就调用一次,可以重复点击,onDestory方法销毁方法。

2、bind方式绑定

AndroidManifest.xml,注册服务器对象

<service android:name="com.example.servicedemo2.MyBindService"></service>

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"> <TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="BindService:" /> <Button
android:onClick="doClick"
android:id="@+id/btn_bindstart"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="BindService" /> <Button
android:onClick="doClick"
android:id="@+id/btn_bindstop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="UnBindService" />
</LinearLayout>

MyBindService.java,创建基于Bind绑定的服务类

package com.example.servicedemo2;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder; public class MyBindService extends Service{ @Override //绑定方法
public IBinder onBind(Intent intent) {
System.out.println("Bind_onBind");
return null;
} @Override //创建时调用
public void onCreate() {
System.out.println("Bind_onCreate");
super.onCreate();
} @Override //销毁时调用
public void onDestroy() {
System.out.println("Bind_onDestroy");
super.onDestroy();
} @Override //解绑时调用
public boolean onUnbind(Intent intent) {
System.out.println("Bind_onUnbind");
return super.onUnbind(intent);
} }

main.java,后台Activity代码

package com.example.servicedemo2;

import android.app.Activity;
import android.app.Service;
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 { private ServiceConnection conn = new ServiceConnection() { @Override
public void onServiceDisconnected(ComponentName name) { } @Override
public void onServiceConnected(ComponentName name, IBinder service) { }
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
} public void doClick(View v){
switch(v.getId()){
case R.id.btn_bindstart:
Intent intent = new Intent(MainActivity.this, MyBindService.class);
bindService(intent, conn,Service.BIND_AUTO_CREATE);
break;
case R.id.btn_bindstop:
unbindService(conn);
break;
}
}
}

  启动和结束按钮不能被多次点击,必须启动后才能释放,1对1,启动服务后,退出应用程序,也会报错,必须先释放绑定的服务源对象

3、activity调用service中的方法

main.xml 主页面,定义六个按钮,bind和unbind为绑定service,paly,pause,next,prev为调用service中的四个方法

<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"> <TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="BindService:" /> <Button
android:onClick="doClick"
android:id="@+id/btn_bindstart"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="BindService" /> <Button
android:onClick="doClick"
android:id="@+id/btn_bindstop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="UnBindService" /> <TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="播放器服务" /> <Button
android:onClick="musicClick"
android:id="@+id/btnPlay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="播放" /> <Button
android:onClick="musicClick"
android:id="@+id/btnPause"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="暂停" /> <Button
android:onClick="musicClick"
android:id="@+id/btnNext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="下一首" /> <Button
android:onClick="musicClick"
android:id="@+id/btnPrev"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="上一首" /> </LinearLayout>

mybindservice.java 服务方法

package com.example.servicedemo2;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder; public class MyBindService extends Service{ //继承抽象类Binder
public class MyBinder extends Binder{ //定义获取绑定服务的方法
public MyBindService getService(){
return MyBindService.this;
}
} @Override //绑定方法
public IBinder onBind(Intent intent) {
System.out.println("Bind_onBind");
return new MyBinder();
} @Override //创建时调用
public void onCreate() {
System.out.println("Bind_onCreate");
super.onCreate();
} @Override //销毁时调用
public void onDestroy() {
System.out.println("Bind_onDestroy");
super.onDestroy();
} @Override //解绑时调用
public boolean onUnbind(Intent intent) {
System.out.println("Bind_onUnbind");
return super.onUnbind(intent);
} //添加自定义的方法 //播放方法
public void play(){
System.out.println("Play");
} //暂停方法
public void pause(){
System.out.println("Pause");
} //下一首
public void next(){
System.out.println("Next");
} //上一首
public void prev(){
System.out.println("Prev");
}
}

main.java 后台代码

package com.example.servicedemo2;

import com.example.servicedemo2.MyBindService.MyBinder;

import android.app.Activity;
import android.app.Service;
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 b; private ServiceConnection conn = new ServiceConnection() { @Override //当启动源和Service的连接意外丢失的时候会调用这个方法
//当Service崩溃了,或者被强行杀死了,如果接触了绑定就不会被调用
public void onServiceDisconnected(ComponentName name) { } //activity和service之间的参数传递。
@Override //当启动源跟Service成功连接之后将会自动调用这个方法
public void onServiceConnected(ComponentName name, IBinder binder) {
b = (MyBindService.MyBinder)binder;
}
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
} //声明周期事件
public void doClick(View v){
switch(v.getId()){
case R.id.btn_bindstart:
Intent intent = new Intent(MainActivity.this, MyBindService.class);
bindService(intent, conn,Service.BIND_AUTO_CREATE);
break;
case R.id.btn_bindstop:
unbindService(conn);
break;
}
} public void musicClick(View v){
//通过b.xxx调用service中的方法
switch(v.getId()){
case R.id.btnPlay:
b.getService().play();
break;
case R.id.btnPause:
b.getService().pause();
break;
case R.id.btnNext:
b.getService().next();
break;
case R.id.btnPrev:
b.getService().prev();
break;
}
}
}

AndroidManifest.xml注册service对象

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.servicedemo2"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" /> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.servicedemo2.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.example.servicedemo2.MyBindService"></service>
</application>
</manifest>

Android学习(十四) Service组件的更多相关文章

  1. android学习十四(android的接收短信)

    收发短信是每一个手机主要的操作,android手机当然也能够接收短信了. android系统提供了一系列的API,使得我们能够在自己的应用程序里接收和发送短信. 事实上接收短信主要是利用我们前面学过的 ...

  2. android 学习十四 探索安全性和权限

    1.部署安全性:应用程序必须使用数字证书才能安装到设备上. 2.执行期间的安全性:    2.1 使用独立进程    2.2 使用固定唯一用户ID    2.3  申明性权限模型   3数字证书   ...

  3. 五、Android学习第四天补充——Android的常用控件(转)

    (转自:http://wenku.baidu.com/view/af39b3164431b90d6c85c72f.html) 五.Android学习第四天补充——Android的常用控件 熟悉常用的A ...

  4. 四、Android学习第四天——JAVA基础回顾(转)

    (转自:http://wenku.baidu.com/view/af39b3164431b90d6c85c72f.html) 四.Android学习第四天——JAVA基础回顾 这才学习Android的 ...

  5. Bootstrap入门(十四)组件8:媒体对象

    Bootstrap入门(十四)组件8:媒体对象 这是一个抽象的样式,用以构建不同类型的组件,这些组件都具有在文本内容的左或右侧对齐的图片(就像博客评论或 Twitter 消息等). 1.基本样式 2. ...

  6. Android笔记三十四.Service综合实例二

    综合实例2:client訪问远程Service服务 实现:通过一个button来获取远程Service的状态,并显示在两个文本框中. 思路:如果A应用须要与B应用进行通信,调用B应用中的getName ...

  7. android学习日记20--连接组件之Intent和IntentFilter

    上次刚了解完Android的四大组件,现在学习组件间通信的Intent和IntentFilter 一.Intent 1.简述 Intent(意图)在应用程序运行时连接两个不同组件,是一种运行时的绑定机 ...

  8. android学习日记19--四大组件之Services(服务)

    一个Android应用主要由四个基本组件组成,Android四大基本组件分别是Activity,Content Provider内容提供者,Service服务,BroadcastReceiver广播接 ...

  9. Android学习总结(二)——Service基本概念和生命周期

    好了,前面我们已经学习了Activity的知识,相信大家也有一定的理解,但是还是不能放松,Android四大组件,我们才学习了一个而已,接下我们继续学习Service.计划总结如下内容: 一.Serv ...

  10. android学习笔记56——Service

    Service四大组件之一,需要在AndroidMainfest.xml中添加相关配置,运行于后台,不与用户进行交换,没有UI... 配置时可通过<intent-filter.../>元素 ...

随机推荐

  1. CodeVs1515 跳

    题目描述 Description 邪教喜欢在各种各样空间内跳. 现在,邪教来到了一个二维平面.在这个平面内,如果邪教当前跳到了(x,y),那么他下一步可以选择跳到以下4个点:(x-1,y), (x+1 ...

  2. 2590: [Usaco2012 Feb]Cow Coupons

    2590: [Usaco2012 Feb]Cow Coupons Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 306  Solved: 154[Su ...

  3. 自定义View Layout过程 (3)

    目录 目录 1. 知识基础 具体请看我写的另外一篇文章:(1)自定义View基础 - 最易懂的自定义View原理系列 2. 作用 计算View视图的位置. 即计算View的四个顶点位置:Left.To ...

  4. SQL的四种连接查询(转)

    原文转自 https://blog.csdn.net/wangjingna/article/details/48765931

  5. cocos2d programming guide翻译(12)

    http://bbs.tairan.com/thread-807-1-1.html 导演缓冲信息支持cocos2d v0.99.4和更新的版本颜色缓冲这个默认的缓冲时RGB565.它是一个16位的缓冲 ...

  6. Linux下用gSOAP开发Web Service服务端和客户端程序(一)

    1.功能说明: 要开发的Web Service功能非常简单,就是一个add函数,将两个参数相加,返回其和. 2.C版本的程序: (1)头文件:SmsWBS.h,注释部分不可少,url部分的IP必须填写 ...

  7. 通过GitHub部署项目到Nginx服务器

    1.更新源: 2.安装nginx 3.安装成功 4.DNS域名解析 5.访问域名就会找到相应IP地址的主机,一个IP可对应多个域名 6.提交到gitHub 复制这两行 填上邮箱和密码 7.提交成功 8 ...

  8. JAVA SERVLET 属性范围样例

    package com.jeelearning.servlet; import java.io.IOException; import javax.servlet.RequestDispatcher; ...

  9. [BZOJ1044][HAOI2008]木棍分割 二分+贪心+dp+前缀和优化

    1044: [HAOI2008]木棍分割 Time Limit: 10 Sec  Memory Limit: 162 MB Submit: 4112  Solved: 1577 [Submit][St ...

  10. POJ 2482 Stars in Your Window 离散化+扫描法 线段树应用

    遇见poj上最浪漫的题目..题目里图片以上几百词为一篇模板级英文情书.这情感和细腻的文笔深深地打动了我..不会写情书的童鞋速度进来学习.传送门 题意:坐标系内有n个星星,每个星星都有一个亮度c (1& ...