android Service(一)
来源:互联网 发布:python初学者书籍推荐 编辑:程序博客网 时间:2024/05/12 01:06
原文:http://marshal.easymorse.com/archives/1564
android SDK提供了Service,用于类似*nix守护进程或者windows的服务。
Service有两种类型:
- 本地服务(Local Service):用于应用程序内部
- 远程服务(Remote Sercie):用于android系统内部的应用程序之间
前者用于实现应用程序自己的一些耗时任务,比如查询升级信息,并不占用应用程序比如Activity所属线程,而是单开线程后台执行,这样用户体验比较好。
后者可被其他应用程序复用,比如天气预报服务,其他应用程序不需要再写这样的服务,调用已有的即可。
一、本地服务示例
1.1、编写不需和Activity交互的本地服务示例
本地服务编写比较简单。首先,要创建一个Service类,该类继承android的Service类。这里写了一个计数服务的类,每秒钟为计数器加一。在服务类的内部,还创建了一个线程,用于实现后台执行上述业务逻辑。
package com.cn.example;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() { @Override public void run() { while (!threadDisable) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } count++; Log.v("CountService", "Count is " + count); } } }).start(); } @Override public void onDestroy() { super.onDestroy(); this.threadDisable = true; Log.v("CountService", "on destroy"); } public int getCount() { return count; }}
需要将该服务注册到配置文件AndroidManifest.xml中,否则无法找到:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.cn.example" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".LocalServiceDemoActivity" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name="CountService"></service> </application></manifest>
在Activity中启动和关闭本地服务。
package com.cn.example;import android.app.Activity;import android.content.Intent;import android.os.Bundle;/** * 本地服务 */public class LocalServiceDemoActivity extends Activity { /** Called when the activity is first created. */ @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)); }}
可通过日志查看到后台线程打印的计数内容。
代码下载地址为:http://download.csdn.net/detail/niejing654092427/4580614
1.2、编写本地服务和Activity交互的示例
上面的示例是通过startService和stopService启动关闭服务的。适用于服务和activity之间没有调用交互的情况。如果之间需要传递参数或者方法调用。需要使用bind和unbind方法。
具体做法是,服务类需要增加接口,比如ICountService,另外,服务类需要有一个内部类,这样可以方便访问外部类的封装数据,这个内部类需要继承Binder类并实现ICountService接口。还有,就是要实现Service的onBind方法,不能只传回一个null了。
这是新建立的接口代码:
package com.example.androidservicetest;public interface ICountService {public abstract int getCount();}
CountService.java
package com.example.androidservicetest;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 mThreadDisable;private int mCount;private ServiceBinder mServiceBinder = new ServiceBinder();@Overridepublic int getCount() {// TODO Auto-generated method stubreturn mCount;}@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn mServiceBinder;}@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();new Thread(new Runnable(){@Overridepublic void run() {// TODO Auto-generated method stubwhile (!mThreadDisable) { try { Thread.sleep(1000); } catch (InterruptedException e) { } mCount++; Log.v("CountService", "Count is " + mCount); }}}).start();} @Overridepublic void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();this.mThreadDisable = true;Log.v("CountService", "onDestroy");}/** * * 内部类 */private class ServiceBinder extends Binder implements ICountService{@Overridepublic int getCount() {// TODO Auto-generated method stubreturn mCount;}}}
服务的注册也要做改动,AndroidManifest.xml文件:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.androidservicetest" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".LocalServiceDemoActivity" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name="CountService"> <intent-filter> <action android:name="com.example.androidservicetest.CountService"/> </intent-filter> </service> </application></manifest>
Acitity代码不再通过startSerivce和stopService启动关闭服务,另外,需要通过ServiceConnection的内部类实现来连接Service和Activity。
package com.example.androidservicetest;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.util.Log;public class LocalServiceDemoActivity extends Activity {private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { countService = (ICountService) service; Log.v("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.example.androidservicetest.CountService"), this.serviceConnection, BIND_AUTO_CREATE); } @Override protected void onDestroy() { super.onDestroy(); this.unbindService(serviceConnection); } }
可通过日志查看到后台线程打印的计数内容。
代码下载地址为:http://download.csdn.net/detail/niejing654092427/4580619
二、远程服务示例
- android Service(一)
- Android Service(一)
- android Service(一)
- Android Service(一)--浅谈Service
- Android Service(一) Service初识
- Android--Service生命周期(一)
- Android service 总结(一)
- Android Service 服务 (一)
- android之service(一)
- Android---Service详解(一)
- android service 学习 (一)
- Android开发-service(一)
- <Android 基础(一)> Service
- Android Service详解(一)
- Android Service 初探(一)
- android Service(一) activity启动Service方式一:startService()
- Android Service 服务(一)—— Service
- Android Service 服务(一)—— Service
- 2012 人民搜索 实习生招聘 笔试题
- socket中网络字节序的处理
- nginx的helloworld模块的helloworld
- android ListView详解
- 隐藏ListCtrl中指定列(拖动不显示)
- android Service(一)
- clojure入门: hello world
- 七夕夜、离别,涵情经河岸
- 关于敏捷开发的两道选择题
- MySQL Migration Toolkit 实现 MSSQL 到 MySQL数据迁移 转载
- uncaught exception: [CKEDITOR.editor] The instance “xxxx” already exists
- 替换Android控件默认样式 (例子:自定义进度条)
- Linux中tty框架与uart框架之间的调用关系剖析
- UICollectionView 讲解