这里主要介绍Service组件的使用。

1、定义一个继承Service的子类

如下:

package com.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder; public class defaultService extends Service {
int mStartMode; // indicates how to behave if the service is killed
IBinder mBinder; // interface for clients that bind
boolean mAllowRebind; // indicates whether onRebind should be used @Override
public void onCreate() {
// The service is being created
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
// The service is starting, due to a call to startService()
return mStartMode;
} @Override
public IBinder onBind(Intent intent) {
// A client is binding to the service with bindService()
return mBinder;
} @Override
public boolean onUnbind(Intent intent) {
// All clients have unbound with unbindService()
return mAllowRebind;
} @Override
public void onRebind(Intent intent) {
// A client is binding to the service with bindService(),
// after onUnbind() has already been called
} @Override
public void onDestroy() {
// The service is no longer used and is being destroyed
}
}

2、在AndroidManifest.xml中使用<service>标签配置该Service

<service android:name="com.service.defaultService">
<intent-filter>
<action android:name="com.service.dService" />
</intent-filter>
</service>

注意:第一个name是service的位置,包括完整的包名和service名。如果包名就是你定义的程序包名,也就是和gen目录下那个包的名字一样的话,直接".service名"就可以了。第二个name是调用service时intent.setAction();中的参数,这个可以随便。

3、Service中定义了如下的生命周期方法:

[1] IBinder onBind(Intent intent):该方法是Service子类必须实现的方法,该方法返回一个IBinder对象,应用程序可通过该对象与Service组件通信 ;

[2] void onCreate():当Service组件第一次被创建后立即回调该方法;

[3]void onDestroy():当Service关闭之前回调该方法;

[4]void onStartCommand(Intent intent,int flags,int startId):该方法的早期版本是onStart(Intent intent,int startId),每次客户端调用startService()方法启动Service时都会回调该方法;

[5]boolean onUnbind(Intent intent):当该Service上绑定的所有客户端断开连接时将会调用该方法

当其它组件通过Context.startService()方法启动Service时,系统会创建一个Service对象,并顺序调用onCreate()方法和onStartCommand()方法,在调用Context.stopService()或stopSelf()之前,Service一直处于运行的状态。如果多次调用startService()方法,系统只会多次调用onStartCommand()方法,不会重复调用onCreate()方法。无论调用了多少次startService()方法,只需调用一次stopService()方法就可以停止该Service。Service对象在销毁之前,onDestroy()方法会被调用,因此与资源释放相关的工作应该在此方法中完成。

3、Service的启动停止

[1]方式一:

当程序通过startService()方法和stopService()方法启动、停止Service()时,Service与访问者之间基本上不存在太多的关联,因此Service和访问者之间也无法进行通信和数据交换。

[2]方式二:

通过bindService()与unbindService()方法启动、停止Service()。

4、方式二详解

bindService(Intent serivce,ServiceConnection connection,int flags)方法启动:

[1]第一个参数通过Intent指定要启动的Service;

[2]第二个参数用于监听访问者与Service之间的连接情况;

该ServiceConnection对象用于监听访问者与Service之间的连接情况,当访问者与Service之间连接成功时,将会回调ServiceConnection对象的onServiceConnected(ComponentName name,IBinder service)方法;当Service所在的进程异常终止或由于其它原因终止时,导致该Service与访问者之间断开连接时,将会回调ServiceConnection对象的onServiceDisconnected(ComponentName name)方法(当主动调用unbindService()方法断开与Service的连接时,不会调用该回调方法)。

注意到ServiceConnection对象的onServiceConnected(ComponentName name,IBinder service)方法中有一个IBinder对象,该对象即实现与被绑定Service之间的通信。

[3]第三个参数指定绑定时是否自动创建Service(如果Service还未创建)。该参数可指定为0(不自动创建)或BIND_AUTO_CREATE(自动创建)。

5、开发Service类时必须提供IBinder onBind(Intent intent)方法

在绑定本地Service的情况下,onBind(Intent intent)方法所返回的IBinder对象将会传给ServiceConnection对象里的onServiceConnected(ComponentName name,IBinder service)方法的service参数,以实现与Service进行通信。

实际上开发时常会采用继承Binder(IBinder的实现类)的方式实现自己的IBinder对象。

package com.service;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder; public class BindService extends Service
{
private int count; //标识Service的运行状态
private boolean quit; //标志Service是否被关闭 //定义onBind()方法所返回的对象
private defaultBinder binder = new defaultBinder();
public class defaultBinder extends Binder
{
public int getCount()
{
//获取Service的运行状态:count
return count;
}
}
@Override
public IBinder onBind(Intent intent)
{
System.out.println("Service is Binded!");
return binder;
} //Service被创建时回调该方法
@Override
public void onCreate()
{
super.onCreate();
System.out.println("Serivce is Created!");
//启动一条新线程,动态改变count值
new Thread()
{
@Override
public void run()
{
while(!quit)
{
try{
Thread.sleep(1000);
}
catch (InterruptedException e){
e.printStackTrace();
}
count++;
}
}
}.start();
} //Service被关闭之前回调该方法
@Override
public void onDestroy()
{
super.onDestroy();
this.quit=true;
System.out.println("Service is Destroyed!");
} //Service断开连接时回调该方法
@Override
public boolean onUnbind(Intent intent)
{
System.out.println("Service is Unbinder");
return true;
}
}

6、接下来在一个Activity中绑定该Service,并在Activity中通过defaultBinder对象访问Service的内部状态。

[1]布局文件如下

<?xml version="1.0" encoding="utf-8"?>
<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=".MainActivity" > <Button
android:id="@+id/bind"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="绑定Service" />
<Button
android:id="@+id/unbind"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="解除绑定" />
<Button
android:id="@+id/status"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="获取Service状态" />
</LinearLayout>

[2]Activity如下:

package com.myandroid;

import com.service.BindService;

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.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast; public class ServiceActivity extends Activity
{
private Button bind,unbind,status;
BindService.defaultBinder binder; //保持所启动的Service的IBinder对象 //定义一个ServiceConnection对象
private ServiceConnection conn=new ServiceConnection()
{
@Override
public void onServiceConnected(ComponentName name, IBinder service)
{
System.out.println("Service connected!");
//获取Service的onBind()方法所返回的MyBinder对象
binder=(BindService.defaultBinder) service;
} @Override
public void onServiceDisconnected(ComponentName name)
{
System.out.println("Service disconnected!");
} };
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.service);
//获取界面按钮
bind=(Button)findViewById(R.id.bind);
unbind=(Button)findViewById(R.id.unbind);
status=(Button)findViewById(R.id.status);
//创建启动Service的Intent
final Intent intent=new Intent(); //第一个参数为context,第二个参数为类名(需指定包名)
intent.setClassName(this, "com.service.BindService");
bind.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
//绑定指定Service
bindService(intent,conn,BIND_AUTO_CREATE);
}
});
unbind.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
//解除绑定Service
unbindService(conn);
}
});
status.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
//获取Service状态信息
Toast.makeText(ServiceActivity.this,"Service的count值为:"+binder.getCount(),Toast.LENGTH_LONG).show();
}
});
}
}

Android 四大组件之 Service(二)的更多相关文章

  1. 【Android开发日记】之入门篇(五)——Android四大组件之Service

    这几天忙着驾校考试,连电脑都碰不到了,今天总算告一段落了~~Service作为Android的服务组件,默默地在后台为整个程序服务,辅助应用与系统中的其他组件或系统服务进行沟通.它跟Activity的 ...

  2. Android四大组件之Service

    Android四大组件之Service Android支持服务的概念,服务是在后台运行的组件,没有用户界面,Android服务可用有与活动独立的生命周期.Android支持两种类型的服务: 本地服务: ...

  3. Android四大组件之一Service介绍-android学习之旅(十二)

    基本概念: service是android四大组件之一,运行在后台执行耗时操作,并不提供用户界面.其他组件如acticity可以通过startService启动该组件,也可以通过bindService ...

  4. Android成长日记-Android四大组件之Service组件的学习

    1.什么是Service? Service是Android四大组件中与Activity最相似的组件,它们都代表可执行的程序,Service与Activity的区别在于:Service一直在后台运行,它 ...

  5. Android 四大组件之service与Broadcast

    Android 四大组件之一:service: Service有五个生命周期:onCreat,onStartCommand, onBind,onUnbind, onDestroy 主要有绑定和非绑定两 ...

  6. Android四大组件之一 -- Service详解

    相信大多数朋友对Service这个名词都不会陌生,没错,一个老练的Android程序员如果连Service都没听说过的话,那确实也太逊了.Service作为Android四大组件之一,在每一个应用程序 ...

  7. Android四大组件:Service

    前言 Service作为Android四大组件之一,应用非常广泛 本文将介绍对Service进行全面介绍(基础认识.生命周期.使用和应用场景) 目录 目录 1. 基础知识 定义:服务,属于Androi ...

  8. Android四大组件之Service浅见

    Service 是Android四大组件之一,可以在不显示界面的情况下在后台运行.还有一个作用是通过AIDL来实现进程间通信. Service的启动方式 Service的启动方式有两种,startSe ...

  9. Android 四大组件之Service

    ---恢复内容开始--- 1,Service的生命周期

  10. 谈Android四大组件之Service篇

    Service简介 Service是Android系统中的四大组件之一,它是一种长生命周期的,没有可视化界面,运行于后台的一种服务程序.Service必须在AndroidManifest.xml中声明 ...

随机推荐

  1. Vue集成腾讯地图和几何库

    关于Vue中如何引入腾讯地图,百度搜索中的结果已经非常明确: /** * 腾讯地图. * @param key * @returns {Promise<any>} * @construct ...

  2. 使用HAproxy如何实现web站点的动静分离

    HAProxy提供高可用性.负载均衡以及基于TCP和HTTP应用的代理,支持虚拟主机,它是免费.快速并且可靠的一种解决方案.      HAProxy特别 适用于那些负载特大的web站点,这些站点通常 ...

  3. Git_操作标签

    如果标签打错了,也可以删除: $ git tag -d v0.1 Deleted tag 'v0.1' (was e078af9) 因为创建的标签都只存储在本地,不会自动推送到远程.所以,打错的标签可 ...

  4. better-scroll不生效原因

    在vue项目中运用better-scroll插件进行上拉加载的功能时,页面拉不动. html结构: <div class="wrapper" ref="wrappe ...

  5. 【原】移动web资源整理(安卓、ios移动端兼容性问题归整)

     meta基础知识 H5页面窗口自动调整到设备宽度,并禁止用户缩放页面 <meta name="viewport" content="width=device-wi ...

  6. C#程序集系列12,C#编译器和CLR如何找寻程序集

    本篇体验C#编译器和CLR运行时如何查找程序集,并自定义CLR运行时查找程序集的方式. □ C#编译器和CLR运行时如何查找程序集 C#编译器在哪里?--在C:\Windows\Microsoft.N ...

  7. 详解Linux中CentOS6.8下解压安装mysql-5.7.14

    原文:http://blog.csdn.net/yangle4695/article/details/52185859 mysql下载地址:http://dev.mysql.com/downloads ...

  8. QDAC

    QDAC GITHUB: svn://www.qdac.cc/QDAC3 包括QMsgPack\QJson\QWoker...等序列和事件调度控件.

  9. Selenium2+python自动化49-判断文本(text_to_be_present_in_element)

    前言 在做结果判断的时候,经常想判断某个元素中是否存在指定的文本,如登录后判断页面中是账号是否是该用户的用户名. 在前面的登录案例中,写了一个简单的方法,但不是公用的,在EC模块有个方法是可以专门用来 ...

  10. struts2点滴记录

    1.s:textfield 赋值方法 <s:textfield name="Tname" value="%{#session.Teacher.name}" ...