欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Service Activity的三种交互方式(详解)

程序员文章站 2024-03-04 20:35:18
service有两种类型: 本地服务(local service):用于应用程序内部 远程服务(remote sercie):用于android系统内部的应用程序之间...

service有两种类型:

本地服务(local service):用于应用程序内部

远程服务(remote sercie):用于android系统内部的应用程序之间

前者用于实现应用程序自己的一些耗时任务,比如查询升级信息,并不占用应用程序比如activity所属线程,而是单开线程后台执行,这样用户体验比较好。

后者可被其他应用程序复用,比如天气预报服务,其他应用程序不需要再写这样的服务,调用已有的即可。

编写不需和activity交互的本地服务示例

本地服务编写比较简单。首先,要创建一个service类,该类继承android的service类。这里写了一个计数服务的类,每秒钟为计数器加一。在服务类的内部,还创建了一个线程,用于实现后台执行上述业务逻辑。

service代码:

import android.app.service;
import android.content.intent;
import android.os.ibinder;
import android.util.log;


public class countservice extends service {
private boolean threaddisable;
private int count;
@override
public ibinder onbind(intent intent) {
return null;
}
@override
public void oncreate() {
super.oncreate();
new thread(new runnable() {
public void run() {
while (!threaddisable) {
try {
thread.sleep(1000);
} catch (interruptedexception e) {
}
count++;
system.out.println(" countservice count is " + count);
}
}
}).start();
}
@override
public void ondestroy() {
super.ondestroy();
this.threaddisable = true;
log.v(" countservice ", " on destroy ");
}
}
将该服务注册到配置文件androidmanifest.xml中
<service android:name="countservice" />
在activity中启动和关闭本地服务
import android.app.activity;
import android.content.intent;
import android.os.bundle;


public class localservicedemoactivity extends activity {
@override
public void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.main);
this.startservice(new intent(this, countservice.class));
}


@override
protected void ondestroy() {
super.ondestroy();
this.stopservice(new intent(this, countservice.class));
}
}

编写本地服务和activity交互的示例

上面的示例是通过startservice和stopservice启动关闭服务的。适用于服务和activity之间没有调用交互的情况。如果之间需要传递参数或者方法调用。需要使用bind和unbind方法。

具体做法是,服务类需要增加接口,比如icountservice,另外,服务类需要有一个内部类,这样可以方便访问外部类的封装数据,这个内部类需要继承binder类并实现icountservice接口。还有,就是要实现service的

onbind方法,不能只传回一个null了。

新建立的接口代码:

public interface icountservice {
public abstract int getcount();
}

countservice代码:
import android.app.service;
import android.content.intent;
import android.os.binder;
import android.os.ibinder;
import android.util.log;


public class countservice extends service implements icountservice {
private boolean threaddisable;
private int count;
private servicebinder servicebinder = new servicebinder();


public class servicebinder extends binder implements icountservice {
// @override
public int getcount() {
return count;
}
}


@override
public ibinder onbind(intent intent) {
return servicebinder;
}


@override
public void oncreate() {
super.oncreate();
new thread(new runnable() {
// @override
public void run() {
while (!threaddisable) {
try {
thread.sleep(1000);
} catch (interruptedexception e) {
}
count++;
system.out.println("countservice count is " + count);
}
}
}).start();
}


@override
public void ondestroy() {
super.ondestroy();
this.threaddisable = true;
log.v(" countservice ", " on destroy ");
}


// @override
public int getcount() {
return count;
}
}

服务的注册也要做改动,androidmanifest.xml文件:

 <service android:name="countservice" >
      <intent-filter>
        <action android:name="com.phone.jiaohuservice.countservice" />
      </intent-filter>
 </service>

acitity代码不再通过startserivce和stopservice启动关闭服务,另外,需要通过serviceconnection的内部类实现来连接service和activity。
import android.app.activity;
import android.content.componentname;
import android.content.intent;
import android.content.serviceconnection;
import android.os.bundle;
import android.os.ibinder;


public class localservicedemoactivity extends activity {
private serviceconnection serviceconnection = new serviceconnection() {
// @override
public void onserviceconnected(componentname name, ibinder service) {
countservice = (icountservice) service;
system.out.println(" countservice on serivce connected, count is "
+ countservice.getcount());
}


// @override
public void onservicedisconnected(componentname name) {
countservice = null;
}
};


private icountservice countservice;


/** called when the activity is first created. */
@override
public void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.main);
this.bindservice(new intent("com.phone.jiaohuservice.countservice"),
this.serviceconnection, bind_auto_create);
}


@override
protected void ondestroy() {
this.unbindservice(serviceconnection);
super.ondestroy(); // 注意先后
}
}

编写传递基本型数据的远程服务

上面的示例,可以扩展为,让其他应用程序复用该服务。这样的服务叫远程(remote)服务,实际上是进程间通信(rpc)。

这时需要使用android接口描述语言(aidl)来定义远程服务的接口,而不是上述那样简单的java接口。扩展名为aidl而不是java。可用上面的icountservice改动而成icountserivde.aidl,eclipse会自动生成相关的java文件。

远端代码:

icountservice.aidl

package com.phone.remoteservice.aidl;
interface icountservice {
int getcount();
} 

countservice.java

import com.phone.remoteservice.aidl.icountservice;
import android.app.service;
import android.content.intent;
import android.os.ibinder;
import android.os.remoteexception;
import android.util.log;


public class countservice extends service {
private boolean threaddisable;
private int count;
private icountservice.stub servicebinder = new icountservice.stub() {
// @override
public int getcount() throws remoteexception {
return count;
}
};


// @override
public ibinder onbind(intent intent) {
return servicebinder;
}


@override
public void oncreate() {
super.oncreate();
new thread(new runnable() {
// @override
public void run() {
while (!threaddisable) {
try {
thread.sleep(1000);
} catch (interruptedexception e) {
}
count++;
log.i("aa", "---" + count + "---");
}
}
}).start();
}


// @override
public void ondestroy() {
super.ondestroy();
this.threaddisable = true;
log.v(" countservice ", " on destroy ");
}

}

 配置文件androidmanifest.xml

<service android:name=".countservice" >
 <intent-filter>
 <action android:name="com.phone.remoteservice.countservice" />
 </intent-filter>
</service>

本地代码:

拷贝远端代码gen:com.phone.remoteservice.aidl包名及内部生成的icountservice.java文件到本地,注意包名不要变,java文件名也不要变。

测试代码

import com.phone.remoteservice.aidl.icountservice;
import android.os.bundle;
import android.os.ibinder;
import android.os.remoteexception;
import android.app.activity;
import android.content.componentname;
import android.content.intent;
import android.content.serviceconnection;
import android.view.menu;


public class remoteservicetest extends activity {
private icountservice countservice;
private boolean srevicedisable;
/** called when the activity is first created. */
@override
public void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.main);
bindservice(new intent("com.phone.remoteservice.countservice"),
this.serviceconnection, bind_auto_create);
}


@override
protected void ondestroy() {
this.unbindservice(serviceconnection);
srevicedisable = true;
super.ondestroy(); // 注意先后
}


private serviceconnection serviceconnection = new serviceconnection() {
public void onserviceconnected(componentname name, ibinder service) {
countservice = icountservice.stub.asinterface(service);
new thread(new runnable() {
// @override
public void run() {
while (!srevicedisable) {

try {
system.out
.println(" countservice on serivce connected, count is "
+ countservice.getcount());
} catch (remoteexception e) {
e.printstacktrace();
}
try {
thread.sleep(1000);
} catch (interruptedexception e) {
}
}
}
}).start();
}


public void onservicedisconnected(componentname name) {
countservice = null;

}
};
}

在activity中使用服务的差别不大,只需要对serviceconnection中的调用远程服务的方法时,要捕获remoteexception 异常。

这样就可以在同一个应用程序中使用远程服务的方式和自己定义的服务交互了。 如果是另外的应用程序使用远程服务,需要做的是复制上面的aidl文件和相应的包构到应用程序中,其他调用等都一样。

编写传递复杂数据类型的远程服务

远程服务往往不只是传递java基本数据类型。这时需要注意android的一些限制和规定:

1. android支持string和charsequence

2. 如果需要在aidl中使用其他aidl接口类型,需要import,即使是在相同包结构下;

3. android允许传递实现parcelable接口的类,需要import;

4. android支持集合接口类型list和map,但是有一些限制,元素必须是基本型或者上述三种情况,不需要import集合接口类,但是需要对元素涉及到的类型import;

5. 非基本数据类型,也不是string和charsequence类型的,需要有方向指示,包括in、out和inout,in表示由客户端设置,out表示由服务端设置,inout是两者均可设置。

这里将前面的例子中返回的int数据改为复杂数据类型:

import android.os.parcel;
import android.os.parcelable;
public class countbean implements parcelable {
public static final parcelable.creator < countbean > creator = new creator < countbean > () {
@override
public countbean createfromparcel(parcel source) {
countbean bean = new countbean();
bean.count = source.readint();
return bean;
}
@override
public countbean[] newarray( int size) {
return new countbean[size];
}
};
public int count;
@override
public void writetoparcel(parcel dest, int flags) {
dest.writeint( this .count);
}
@override
public int describecontents() {
return 0 ;
}
}

以上就是小编为大家带来的service activity的三种交互方式(详解)的全部内容了,希望对大家有所帮助,多多支持~

上一篇: Android中Parcel用法详解

下一篇: