一、定义

  运行在后台,没有页面,不可见。优先级高于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. Eclipse中使用Maven创建Web时错误

    一.问题描述 使用Eclipse创建Maven项目时,报一下错误,不能创建成功. 二.问题原因 错误详细描述是说 Could not resolve archetype org.apache.mave ...

  2. win8下notepad++无法设置文件关联

  3. libyuv编译(各平台)【转】

    转自:http://blog.csdn.net/wszawsz33/article/details/51669719 版权声明:本文为博主原创文章,未经博主允许不得转载. 目录(?)[-] Getti ...

  4. [Oracle] Setup DataGuard

    Oracle一步步搭建DataGuard DataGuard环境: OS: SuSe 10 Primary DB: IP address:1.1.1.1 user:root passwd:****** ...

  5. Centos 查看硬盘空间

    df -h du -ah --max-depth=1 目录深度为1 -h:以人类可读的方式显示 -a:显示目录占用的磁盘空间大小,还要显示其下目录和文件占用磁盘空间的大小 -s:显示目录占用的磁盘空间 ...

  6. J.U.C并发框架源码阅读(二)AbstractQueuedSynchronizer

    基于版本jdk1.7.0_80 java.util.concurrent.locks.AbstractQueuedSynchronizer 代码如下 /* * ORACLE PROPRIETARY/C ...

  7. 牛客小白月赛3 F 异或【区间交集】

    链接:https://www.nowcoder.com/acm/contest/87/F 来源:牛客网 题目描述 Cwbc想测试一下他的加密协议,以便防止其他人偷看他给XHRlyb的信. Cwbc提出 ...

  8. 洛谷 P1803 凌乱的yyy【经典贪心/选择不相交区间】

    题目背景 快noip了,yyy很紧张! 题目描述 现在各大oj上有n个比赛,每个比赛的开始.结束的时间点是知道的. yyy认为,参加越多的比赛,noip就能考的越好(假的) 所以,他想知道他最多能参加 ...

  9. Codeforces #425 Div2 D

    #425 Div2 D 题意 给出一个树形图,每次询问给出三个点,从其中选择两个作为起始点,一个终点,求从两个起始点出发(走最短路)到达终点经过的共同的点最多的数量. 分析 这种树上点与点之间距离有关 ...

  10. [POI2014]Solar Panels

    题目大意: $T(T\le1000)$组询问,每次给出$A,B,C,D(A,B,C,D\le10^9)$,求满足$A\le x\le B,C\le y\le D$的最大的$\gcd(x,y)$. 思路 ...