android编写Service入门本地和远程调用.docxVIP

  • 1
  • 0
  • 约9.34千字
  • 约 9页
  • 2017-08-29 发布于重庆
  • 举报

android编写Service入门本地和远程调用.docx

android编写Service入门本地和远程调用

android编写Service入门android SDK提供了Service,用于类似*nix守护进程或者windows的服务。Service有两种类型:本地服务(Local Service):用于应用程序内部远程服务(Remote Sercie):用于android系统内部的应用程序之间前者用于实现应用程序自己的一些耗时任务,比如查询升级信息,并不占用应用程序比如Activity所属线程,而是单开线程后台执行,这样用户体验比较好。后者可被其他应用程序复用,比如天气预报服务,其他应用程序不需要再写这样的服务,调用已有的即可。编写不需和Activity交互的本地服务示例本地服务编写比较简单。首先,要创建一个Service类,该类继承android的Service类。这里写了一个计数服务的类,每秒钟为计数器加一。在服务类的内部,还创建了一个线程,用于实现后台执行上述业务逻辑。package com.easymorse;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;publicclass CountService extends Service {privateboolean threadDisable;privateint count; @Overridepublic IBinder onBind(Intent intent) {returnnull; } @Overridepublicvoid onCreate() {super.onCreate();new Thread(new Runnable() { @Overridepublicvoid run() {while (!threadDisable) {try { Thread.sleep(1000); } catch (InterruptedException e) { } count++; Log.v(CountService, Count is + count); } } }).start(); } @Overridepublicvoid onDestroy() {super.onDestroy();this.threadDisable = true; Log.v(CountService, on destroy); }publicint getCount() {return count; }}需要将该服务注册到配置文件AndroidManifest.xml中,否则无法找到:?xml version=1.0 encoding=utf-8?manifest xmlns:android=/apk/res/android package=com.easymorse android:versionCode=1 android:versionName=1.0application android:icon=@drawable/icon android:label=@string/app_nameactivity android:name=.LocalServiceDemoActivity android:label=@string/app_nameintent-filteraction android:name=ent.action.MAIN/category android:name=ent.category.LAUNCHER//intent-filter/activityservice android:name=CountService//applicationuses-sdk android:minSdkVersion=3//manifest在Activity中启动和关闭本地服务。package com.easymorse;import android.app.Activity;import android.content.Intent;import android.os.Bundle;publicclass LocalServiceDemoActivity extends Activity {/** Called when the acti

文档评论(0)

1亿VIP精品文档

相关文档