当前位置:文档之家› Android Service Activity三种交互方式

Android Service Activity三种交互方式

Android Service Activity三种交互方式
Android Service Activity三种交互方式

android SDK提供了Service,用于类似*nix守护进程或者windows的服务。

ervice有两种类型:

本地服务(Local Service):用于应用程序内部

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

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

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

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

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

Java代码:

1.package eoe.easymorse;

2.

3.import android.app.Service;

4.import android.content.Intent;

5.import android.os.IBinder;

6.import android.util.Log;

7.

8.public class CountService extends Service {

9.

10.private boolean threadDisable;

11.

12.private int count;

13.

14.@Override

15.public IBinder onBind(Intent intent) {

16.return null ;

17.}

18.

19.@Override

20.public void onCreate() {

21.super .onCreate();

22.new Thread( new Runnable() {

23.

24.@Override

25.public void run() {

26.while ( ! threadDisable) {

27.try {

28.Thread.sleep( 1000 );

29.} catch (InterruptedException e) {

30.}

31.count ++ ;

32.Log.v( " CountService " , " Count is " + count);

33.}

34.}

35.}).start();

36.}

37.

38.@Override

39.public void onDestroy() {

40.super .onDestroy();

41.this .threadDisable = true ;

42.Log.v( " CountService " , " on destroy " );

43.}

44.

45.public int getCount() {

46.return count;

47.}

48.}

复制代码

需要将该服务注册到配置文件AndroidManifest.xml中,否则无法找到:Java代码:

1.

2.< manifest xmlns:android

="https://www.doczj.com/doc/a94794704.html,/apk/res/android"

3.package ="com.easymorse"

4.android:versionCode ="1"

5.android:versionName ="1.0" >

6.< application android:icon ="@drawable/icon" android:label

="@string/app_name" >

7.< activity android:name =".LocalServiceDemoActivity"

8.android:label ="@string/app_name" >

9.< intent-filter >

10.< action android:name ="android.intent.action.MAIN" />

11.< category android:name ="https://www.doczj.com/doc/a94794704.html,UNCHER" />

12.

13.

14.< service android:name ="CountService" />

15.

16.< uses-sdk android:minSdkVersion ="3" />

17.

复制代码

在Activity中启动和关闭本地服务。

Java代码:

1.package eoe.easymorse;

2.

3.import android.app.Activity;

4.import android.content.Intent;

5.import android.os.Bundle;

6.

7.public class LocalServiceDemoActivity extends Activity {

8./** Called when the activity is first created. */

9.@Override

10.public void onCreate(Bundle savedInstanceState) {

11.super .onCreate(savedInstanceState);

12.setContentView(https://www.doczj.com/doc/a94794704.html,yout.main);

13.

14.this .startService( new Intent( this , CountService. class ));

15.}

16.

17.@Override

18.protected void onDestroy() {

19.super .onDestroy();

20.this .stopService( new Intent( this , CountService. class ));

21.}

22.}

复制代码

可通过日志查看到后台线程打印的计数内容。

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

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

具体做法是,服务类需要增加接口,比如ICountService,另外,服务类需要有一个内部类,这样可以方便访问外部类的封装数据,这个内部类需要继承Binder类并实现ICountService接口。还有,就是要实现Service的onBind方法,不能只传回一个null了。

这是新建立的接口代码:

Java代码:

1.package eoe.easymorse;

2.

3.public interface ICountService {

4.public abstract int getCount();

5.}

6.

7.

8.修改后的CountService代码:

9.

10.package com.easymorse;

11.

12.import android.app.Service;

13.import android.content.Intent;

14.import android.os.Binder;

15.import android.os.IBinder;

16.import android.util.Log;

17.

18.public class CountService extends Service implements ICountService

{

19.

20.private boolean threadDisable;

21.

22.private int count;

23.

24.private ServiceBinder serviceBinder = new ServiceBinder();

25.

26.public class ServiceBinder extends Binder implements

ICountService{

27.@Override

28.public int getCount() {

29.return count;

30.

31.}

32.

33.}

34.

35.@Override

36.

37.public IBinder onBind(Intent intent) {

38.return serviceBinder;

39.}

40.

41.@Override

42.public void onCreate() {

43.super .onCreate();

44.new Thread( new Runnable() {

45.

46.@Override

47.public void run() {

48.while ( ! threadDisable) {

49.try {

50.Thread.sleep( 1000 );

51.} catch (InterruptedException e) {

52.}

53.count ++ ;

54.Log.v( " CountService " , " Count is " + count);

55.}

56.}

57.}).start();

58.}

59.

60.@Override

61.public void onDestroy() {

62.super .onDestroy();

63.this .threadDisable = true ;

64.Log.v( " CountService " , " on destroy " );

65.}

66.

67./* (non-Javadoc)

68.* @see com.easymorse.ICountService#getCount()

69.*/

70.public int getCount() {

71.return count;

72.}

73.

74.}

复制代码

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

Java代码:

1.

2.< manifest xmlns:android

="https://www.doczj.com/doc/a94794704.html,/apk/res/android"

3.package ="com.easymorse" android:versionCode ="1"

android:versionName ="1.0" >

4.< application android:icon ="@drawable/icon" android:label

="@string/app_name" >

5.< activity android:name =".LocalServiceDemoActivity"

6.android:label ="@string/app_name" >

7.< intent-filter >

8.< action android:name ="android.intent.action.MAIN" />

9.< category android:name ="https://www.doczj.com/doc/a94794704.html,UNCHER" />

10.

11.

12.< service android:name ="CountService" >

13.< intent-filter >

14.< action android:name ="com.easymorse.CountService" />

15.

16.

17.

18.< uses-sdk android:minSdkVersion ="3" />

19.

复制代码

Acitity代码不再通过startSerivce和stopService启动关闭服务,另外,需要通过ServiceConnection的内部类实现来连接Service和Activity。

Java代码:

1.package eoe.easymorse;

2.

3.import android.app.Activity;

4.import https://www.doczj.com/doc/a94794704.html,ponentName;

5.import android.content.Intent;

6.import android.content.ServiceConnection;

7.import android.os.Bundle;

8.import android.os.IBinder;

9.import android.util.Log;

10.

11.public class LocalServiceDemoActivity extends Activity {

12.

13.private ServiceConnection serviceConnection = new

ServiceConnection() {

14.

15.@Override

16.public void onServiceConnected(ComponentName name, IBinder

service) {

17.countService = (ICountService) service;

18.Log.v( " CountService " , " on serivce connected, count is "

19.+ countService.getCount());

20.}

21.

22.@Override

23.public void onServiceDisconnected(ComponentName name) {

24.countService = null ;

25.}

26.

27.};

28.

29.private ICountService countService;

30.

31./** Called when the activity is first created. */

32.@Override

33.public void onCreate(Bundle savedInstanceState) {

34.super .onCreate(savedInstanceState);

35.setContentView(https://www.doczj.com/doc/a94794704.html,yout.main);

36.this .bindService( new Intent( " com.easymorse.CountService " ),

37.this .serviceConnection, BIND_AUTO_CREATE);

38.}

39.

40.@Override

41.protected void onDestroy() {

42.

43.this .unbindService(serviceConnection);

44.

45.super .onDestroy(); //注意先后

46.}

47.}

复制代码

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

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

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

Java代码:

1.package com.easymorse;

2.

3.interface ICountService {

4.int getCount();

5.}

复制代码

编写服务(Service)类,稍有差别,主要在binder是通过远程获得的,需要通过桩(Stub)来获取。桩对象是远程对象的本地代理。

Java代码:

1.package eoe.easymorse;

2.

3.import android.app.Service;

4.import android.content.Intent;

5.import android.os.IBinder;

6.import android.os.RemoteException;

7.import android.util.Log;

8.

9.public class CountService extends Service {

10.

11.private boolean threadDisable;

12.

13.private int count;

14.

15.private ICountService.Stub serviceBinder = new

ICountService.Stub() {

16.

17.@Override

18.public int getCount() throws RemoteException {

19.return count;

20.}

21.};

23.@Override

24.public IBinder onBind(Intent intent) {

25.return serviceBinder;

26.}

27.

28.@Override

29.public void onCreate() {

30.super .onCreate();

31.new Thread( new Runnable() {

32.

33.@Override

34.public void run() {

35.while ( ! threadDisable) {

36.try {

37.Thread.sleep( 1000 );

38.} catch (InterruptedException e) {

39.}

40.count ++ ;

41.Log.v( " CountService " , " Count is " + count);

42.}

43.}

44.}).start();

45.}

46.

47.@Override

48.public void onDestroy() {

49.super .onDestroy();

50.this .threadDisable = true ;

51.Log.v( " CountService " , " on destroy " );

52.}

53.}

复制代码

配置文件AndroidManifest.xml和上面的类似,没有区别。

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

Java代码:

1.private ServiceConnection serviceConnection = new

ServiceConnection() {

3.@Override

4.public void onServiceConnected(ComponentName name, IBinder

service) {

5.countService = (ICountService) service;

6.try {

7.Log.v( " CountService " , " on serivce connected, count is "

8.+ countService.getCount());

9.} catch (RemoteException e) {

10.throw new RuntimeException(e);

11.}

12.}

13.

14.@Override

15.public void onServiceDisconnected(ComponentName name) {

16.countService = null ;

17.}

18.

19.};

复制代码

这样就可以在同一个应用程序中使用远程服务的方式和自己定义的服务交互了。

如果是另外的应用程序使用远程服务,需要做的是复制上面的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数据改为复杂数据类型:

Java代码:

1.package eoe.easymorse;

2.

3.import android.os.Parcel;

4.import android.os.Parcelable;

5.

6.public class CountBean implements Parcelable {

7.

8.public static final Parcelable.Creator < CountBean > CREATOR = new

Creator < CountBean > () {

9.

10.@Override

11.public CountBean createFromParcel(Parcel source) {

12.CountBean bean = new CountBean();

13.bean.count = source.readInt();

14.return bean;

15.}

16.

17.@Override

18.public CountBean[] newArray( int size) {

19.return new CountBean[size];

20.}

21.

22.};

23.

24.public int count;

25.

26.@Override

27.public void writeToParcel(Parcel dest, int flags) {

28.dest.writeInt( this .count);

29.}

30.

31.@Override

32.public int describeContents() {

33.return 0 ;

34.}

35.

36.}

复制代码

相关主题
文本预览
相关文档 最新文档