Android 四大组件之 Service(二)
这里主要介绍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(二)的更多相关文章
- 【Android开发日记】之入门篇(五)——Android四大组件之Service
这几天忙着驾校考试,连电脑都碰不到了,今天总算告一段落了~~Service作为Android的服务组件,默默地在后台为整个程序服务,辅助应用与系统中的其他组件或系统服务进行沟通.它跟Activity的 ...
- Android四大组件之Service
Android四大组件之Service Android支持服务的概念,服务是在后台运行的组件,没有用户界面,Android服务可用有与活动独立的生命周期.Android支持两种类型的服务: 本地服务: ...
- Android四大组件之一Service介绍-android学习之旅(十二)
基本概念: service是android四大组件之一,运行在后台执行耗时操作,并不提供用户界面.其他组件如acticity可以通过startService启动该组件,也可以通过bindService ...
- Android成长日记-Android四大组件之Service组件的学习
1.什么是Service? Service是Android四大组件中与Activity最相似的组件,它们都代表可执行的程序,Service与Activity的区别在于:Service一直在后台运行,它 ...
- Android 四大组件之service与Broadcast
Android 四大组件之一:service: Service有五个生命周期:onCreat,onStartCommand, onBind,onUnbind, onDestroy 主要有绑定和非绑定两 ...
- Android四大组件之一 -- Service详解
相信大多数朋友对Service这个名词都不会陌生,没错,一个老练的Android程序员如果连Service都没听说过的话,那确实也太逊了.Service作为Android四大组件之一,在每一个应用程序 ...
- Android四大组件:Service
前言 Service作为Android四大组件之一,应用非常广泛 本文将介绍对Service进行全面介绍(基础认识.生命周期.使用和应用场景) 目录 目录 1. 基础知识 定义:服务,属于Androi ...
- Android四大组件之Service浅见
Service 是Android四大组件之一,可以在不显示界面的情况下在后台运行.还有一个作用是通过AIDL来实现进程间通信. Service的启动方式 Service的启动方式有两种,startSe ...
- Android 四大组件之Service
---恢复内容开始--- 1,Service的生命周期
- 谈Android四大组件之Service篇
Service简介 Service是Android系统中的四大组件之一,它是一种长生命周期的,没有可视化界面,运行于后台的一种服务程序.Service必须在AndroidManifest.xml中声明 ...
随机推荐
- hdu 1394 Minimum Inversion Number 逆序数/树状数组
Minimum Inversion Number Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://acm.hdu.edu.cn/showprob ...
- UVALive 4425 Another Brick in the Wall 暴力
C - Another Brick in the Wall Time Limit:3000MS Memory Limit:0KB 64bit IO Format:%lld & ...
- Spring Batch 批处理框架介绍
前言 在大型的企业应用中,或多或少都会存在大量的任务需要处理,如邮件批量通知所有将要过期的会员,日终更新订单信息等.而在批量处理任务的过程中,又需要注意很多细节,如任务异常.性能瓶颈等等.那么,使用一 ...
- phpunit Cannot redeclare class PHPUnit_Runner_Version
- 【Go入门教程6】struct类型(struct的匿名字段)
struct Go语言中,也和C或者其他语言一样,我们可以声明新的类型,作为其它类型的属性或字段的容器.例如,我们可以创建一个自定义类型person代表一个人的实体.这个实体拥有属性:姓名和年龄.这样 ...
- MVC扩展控制器工厂,通过实现IControllerFactory,根据action名称生成不同的Controller
关于控制器工厂的扩展,要么通过实现IControllerFactory接口,要么通过继承DefaultControllerFactory.本篇中,我想体验的是: 1.当请求经过路由,controlle ...
- x-superobject
x-superobject GITHUB: https://github.com/onryldz/x-superobject **Delphi Cross Platform Rapid JSON**- ...
- 【Linux】在虚拟机上安装CentOS7
在配置好的机子上,可以装个双系统,但是在我自己的本子上,磁盘读写太垃圾了,连压缩卷 都执行不了,分不出空间,装不了CentOS系统,没办法,采用虚拟机的方式,把它转起来. -------------- ...
- 算法:堆排序(Heap Sort)
备注 考虑到 Heap 的特性,很容易想到将其用作排序的用处,为了提高效率需要适当的改进一下,如:in place remove 和 in place move down. 代码 using Syst ...
- Selenium2+python自动化41-绕过验证码(add_cookie)
前言 验证码这种问题是比较头疼的,对于验证码的处理,不要去想破解方法,这个验证码本来就是为了防止别人自动化登录的.如果你能破解,说明你们公司的验证码吗安全级别不高,那就需要提高级别了. 对于验证码,要 ...