Android(安卓)Service
android.app.Service类的公共函数有:
Application getApplication();
abstract IBinder onBind(Intent intent);
void onConfigurationChanged(Configuration newConfig);
void onCreate();
void onDestroy();
void onLowMemory();
void onRebind(Intent intent);
void onStart(Intent intent, int startId);
boolean onUnbind(Intent intent);
final void setForeground(boolean isForeground);
final void stopSelf();
final void stopSelf(int startId);
final boolean stopSelfResult(int startId);
getApplication()函数返回实现service的application.
onBind() 方法为运行在设备中的外在程序提供一个与服务对话的一个接口。
onConfigurationChanged() 允许service重新配置自己如果设备配置改变了。
系统调用onCreate(), 然后调用onStart(), 当服务停止时调用onDestroy()。
stopSelf() 为程序提供终止服务的接口.
本地服务和远程服务有些重要区别。如果service被严格用在同一个进程中的组件中,那么Context.startService()启用服务。
如果服务支持onBind()函数,那么它是远程服务可以被其他进程调用(Context.bindService()).我们也称远程service为AIDL支持的服务因为客户端用AIDL与服务通讯。
尽管android.app.Service的接口同时支持两种服务,但是最好还是只适用其中一种。
创建一个AIDLservice,执行如下任务:
1.写一个AIDL文件定义你的对客户端接口,使用Android工程相同的package。
2.实现服务并且在onBind()方法中返回接口(可以扩展Stub类)。
3.添加服务配置到你的AndroidManifest.xml文件中。
有以下注意点:
1.我们在AIDL中定义的接口在生成的代码中作为接口实现。
2.一个名称为Stub 的static final abstract类扩展了android.os.Binder并且实现了定义的接口。
3.一个名称为Proxy的内部类实现了接口代理Stub类。
4.AIDL文件必须保存在生成的文件对应的包内。
在客户端程序调用服务:
将AIDL文件拷贝到客户工程文件包中。拥有了AIDL服务,你需要提供接口ServiceConnection的实现。onServiceConnected(ComponentName name, IBinder service)和onServiceDisconnected(ComponentName name)分别在对服务的连接建立和销毁时调用。
在我们调用bindService()函数时,可以传递该实现类的实例。这样就可以获得该服务。
因为bindService()是异步的,平台提供ServiceConnection回调函数这样我们就知道什么时候服务开始和什么时候服务已经结束。
AIDL服务实现了AIDL协议,而客户端程序绑定了AIDL定义。服务通过调用onBind()方法AIDL接口。客户端程序通过调用bindService()绑定AIDL服务,通过调用unbindService()解除同服务的联系。
更多相关文章
- 为什么 Dialog 不能用 Application 的 Context
- Android各种调用
- 【总结备用】Android(安卓)获取正在运行的任务和服务
- Android(安卓)Timer,TimerTask简单的使用
- Android异步请求
- android手势滑动——左右滑动效果实现
- Android(安卓)中调用 其他 app 的 url 协议
- Android(安卓)onMeasure、Measure、measureChild、measureChildr
- android inputreader 部分对event数据的处理