android服务的原理,android service原理
整体考虑:
两种方式启动服务startService和bindService。
startService方式,不需要service返回数据,通过AMS将数据转发给Service即可,异步。简化考虑,AMS作为转发中介,需要维护service列表,以便于将数据转发给service,因此service在启动之后需要告知AMS--publishService;AMS和service的交互是跨进程操作,需要使用Binder方式传递数据,所以通过publishService传递给AMS的数据中需要包含一个Binder对象(或者直接通过IApplicationThread执行,那么需要传递进来一个查找service的token);要做转发因此需要进行路由,那么很重要的一部分是如何实现路由,查找到对应的service?通过intent来查找,如果intent指定了componentName,那么就能精确的查找到对应的service,如果没有指定,可以通过action,type,data等进行匹配,那么匹配的对象是一组组的intent-filter,因此ams对service进行索引时与intent-filter有关,那么是否就是以intent-filter为key呢?
如果service是首次启动,ams中service列表肯定是匹配不到的,需要查找到对应的进程,所有的service都在manifest中注册过,因此可以通过PMS来进行查找,获取到的信息中会包含进程信息和intent-filter等信息。找到对应的进程后,需要检测进程是否存活,存活的进程都会持有IApplicationThread对象,可以作为一个依据,如果进程没有启动,需要把service加入mPendingService队列,启动进程,启动进程之后app调用AMS#attachApplication,AMS会回调bindApplication,之后再启动四大组件之类的;如果进程已经启动,通过realStartService启动service。在service的生命周期至少有两部分,一个为onCreate,一个为onStartCommand,因此onCreate之后,需要通过AMS,再继续执行serviceDoneExecuting通知更新service状态。
startservice代码
关键类:ServiceRecord,ServiceRecord.StartItem对象
// ServiceRecord 为IBinder 对象,并且定义了重新拉起的次数等
final class ServiceRecord extends Binder implements ComponentName.WithComponentName {
private static final String TAG = TAG_WITH_CLASS_NAME ? "ServiceRecord" : TAG_AM;
// Maximum number of delivery attempts before giving up.
static final int MAX_DELIVERY_COUNT = 3;
// Maximum number of times it can fail during execution before giving up.
static final int MAX_DONE_EXECUTING_COUNT = 6;
final ArrayMap bindings
= new ArrayMap();
// All active bindings to the service.
final ArrayMap> connections
= new ArrayMap>();
static class StartItem {
final ServiceRecord sr;
final boolean taskRemoved;
final int id;
final int callingId;
final Intent intent;
final ActivityManagerService.NeededUriGrants neededGrants;
long deliveredTime;
int deliveryCount;
int doneExecutingCount;
UriPermissionOwner uriPermissions;
String stringName; // caching of toString
}
}
ServiceRecord 为IBinder 对象,并且定义了重新拉起的次数等。
bindservice代码
关键类:ContextImpl,ServiceConnection
contextImpl#bindService---->contextImpl.bindServiceCommon
private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags,
UserHandle user) {
IServiceConnection sd;
if (mPackageInfo != null) {
sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(),
mMainThread.getHandler(), flags);
}
validateServiceIntent(service);
try {
IBinder token = getActivityToken();
//省略一些代码。
service.prepareToLeaveProcess();
int res = ActivityManagerNative.getDefault().bindService(
mMainThread.getApplicationThread(), getActivityToken(),
service, service.resolveTypeIfNeeded(getContentResolver()),
sd, flags, user.getIdentifier());
if (res < 0) {
throw new SecurityException(
"Not allowed to bind to service " + service);
}
return res != 0;
} catch (RemoteException e) {
return false;
}
}
其中sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(),
mMainThread.getHandler(), flags);
可以看到代码中也调用了service.resolveTypeIfNeeded(getContentResolver(),接下来代码转入AMS中。
AMS#bindService--> ActiveService#realStartServiceLocked
private final void realStartServiceLocked(ServiceRecord r,
ProcessRecord app, boolean execInFg) throws RemoteException {
if (app.thread == null) {
throw new RemoteException();
}
requestServiceBindingsLocked(r, execInFg);
}
requestServiceBindingLocked:
private final boolean requestServiceBindingLocked(ServiceRecord r,
IntentBindRecord i, boolean execInFg, boolean rebind) {
if (r.app == null || r.app.thread == null) {
// If service is not currently running, can't yet bind.
return false;
}
if ((!i.requested || rebind) && i.apps.size() > 0) {
try {
bumpServiceExecutingLocked(r, execInFg, "bind");
r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
r.app.repProcState);
if (!rebind) {
i.requested = true;
}
i.hasBound = true;
i.doRebind = false;
} catch (RemoteException e) {
if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
return false;
}
}
return true;
}
通过 r.app.thread#scheduleBindService给应用进程发送消息
public final void scheduleBindService(IBinder token, Intent intent,
boolean rebind, int processState) {
updateProcessState(processState, false);
BindServiceData s = new BindServiceData();
s.token = token;
s.intent = intent;
s.rebind = rebind;
Binder.getCallingPid());
sendMessage(H.BIND_SERVICE, s);
}
接下来转入service所在的进程:
case BIND_SERVICE:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
handleBindService((BindServiceData)msg.obj);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
handleBindService:
private void handleBindService(BindServiceData data) {
//从记录中获取一个service对象,每次启动Service,系统都会记录到mServices中
Service s = mServices.get(data.token);
if (s != null) {
try {
data.intent.setExtrasClassLoader(s.getClassLoader());
try {
//判断service是否未绑定过了
if (!data.rebind) {
//没有绑定需要走onBind
IBinder binder = s.onBind(data.intent);
ActivityManagerNative.getDefault().publishService(
data.token, data.intent, binder);
} else {
//绑定过需要走onRebind
s.onRebind(data.intent);
ActivityManagerNative.getDefault().serviceDoneExecuting(
data.token, 0, 0, 0);
}
ensureJitEnabled();
} catch (RemoteException ex) {
}
} catch (Exception e) {
if (!mInstrumentation.onException(s, e)) {
throw new RuntimeException(
"Unable to bind to service " + s
+ " with " + data.intent + ": " + e.toString(), e);
}
}
}
}
其中的data.token为AMS中使用的ServiceRecord,前面提到继承自Binder。依据是否绑定过,决定执行onBind还是onReBind,前者会调用AMS#publishService,后者会调用AMS#serviceDoneExecuting方法。
publishService中调用了ActiveService#publishServiceLocked
for (int conni=r.connections.size()-1; conni>=0; conni--) {
ArrayList clist = r.connections.valueAt(conni);
for (int i=0; i
ConnectionRecord c = clist.get(i);
if (!filter.equals(c.binding.intent.intent)) {
if (DEBUG_SERVICE) Slog.v(
TAG, "Not publishing to: " + c);
if (DEBUG_SERVICE) Slog.v(
TAG, "Bound intent: " + c.binding.intent.intent);
if (DEBUG_SERVICE) Slog.v(
TAG, "Published intent: " + intent);
continue;
}
if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
try {
c.conn.connected(r.name, service);
} catch (Exception e) {
Slog.w(TAG, "Failure sending service " + r.name +
" to connection " + c.conn.asBinder() +
" (in " + c.binding.client.processName + ")", e);
}
}
}
ConnectionRecord中保存有IServiceConnection,前面提到在bindService时,根据ServiceConnection,生成ServiceDispatcher会以Context为单位管理ServiceConnection,LoadedApk对广播和ContentProvider也有类似的管理逻辑。
public final IServiceConnection getServiceDispatcher(ServiceConnection c,
Context context, Handler handler, int flags) {
synchronized (mServices) {
LoadedApk.ServiceDispatcher sd = null;
ArrayMap map = mServices.get(context);
if (map != null) {
sd = map.get(c);
}
if (sd == null) {
sd = new ServiceDispatcher(c, context, handler, flags);
if (map == null) {
map = new ArrayMap();
mServices.put(context, map);
}
map.put(c, sd);
} else {
sd.validate(context, handler);
}
return sd.getIServiceConnection();
}
}
getIServiceConnection中以弱引用的方式持有mDispatcher,原因为何?因为InnerConnection是ServiceDispatcher静态内部类,而不是内部类。(代码组织方式)
static final class ServiceDispatcher {
private final ServiceDispatcher.InnerConnection mIServiceConnection;
private final ServiceConnection mConnection;
private final Context mContext;
private final Handler mActivityThread;
private final ServiceConnectionLeaked mLocation;
private final int mFlags;
private RuntimeException mUnbindLocation;
private boolean mForgotten;
private static class ConnectionInfo {
IBinder binder;
IBinder.DeathRecipient deathMonitor;
}
private static class InnerConnection extends IServiceConnection.Stub {
final WeakReference mDispatcher;
InnerConnection(LoadedApk.ServiceDispatcher sd) {
mDispatcher = new WeakReference(sd);
}
public void connected(ComponentName name, IBinder service, boolean dead)
throws RemoteException {
LoadedApk.ServiceDispatcher sd = mDispatcher.get();
if (sd != null) {
sd.connected(name, service, dead);
}
}
}
private final ArrayMap mActiveConnections
= new ArrayMap();
ServiceDispatcher(ServiceConnection conn,
Context context, Handler activityThread, int flags) {
mIServiceConnection = new InnerConnection(this);
mConnection = conn;
mContext = context;
mActivityThread = activityThread;
mLocation = new ServiceConnectionLeaked(null);
mLocation.fillInStackTrace();
mFlags = flags;
}
ServiceDispatcher#connected:
public void connected(ComponentName name, IBinder service, boolean dead) {
if (mActivityThread != null) {
mActivityThread.post(new RunConnection(name, service, 0, dead));
} else {
doConnected(name, service, dead);
}
}
public void doConnected(ComponentName name, IBinder service, boolean dead) {
ServiceDispatcher.ConnectionInfo old;
ServiceDispatcher.ConnectionInfo info;
synchronized (this) {
if (mForgotten) {
// We unbound before receiving the connection; ignore
// any connection received.
return;
}
old = mActiveConnections.get(name);
if (old != null && old.binder == service) {
// Huh, already have this one. Oh well!
return;
}
if (service != null) {
// A new service is being connected... set it all up.
info = new ConnectionInfo();
info.binder = service;
info.deathMonitor = new DeathMonitor(name, service);
try {
service.linkToDeath(info.deathMonitor, 0);
mActiveConnections.put(name, info);
} catch (RemoteException e) {
// This service was dead before we got it... just
// don't do anything with it.
mActiveConnections.remove(name);
return;
}
} else {
// The named service is being disconnected... clean up.
mActiveConnections.remove(name);
}
if (old != null) {
old.binder.unlinkToDeath(old.deathMonitor, 0);
}
}
// If there was an old service, it is now disconnected.
if (old != null) {
mConnection.onServiceDisconnected(name);
}
if (dead) {
mConnection.onBindingDied(name);
}
// If there is a new viable service, it is now connected.
if (service != null) {
mConnection.onServiceConnected(name, service);
} else {
// The binding machinery worked, but the remote returned null from onBind().
mConnection.onNullBinding(name);
}
}
通过IServiceConnection持有的ServiceDispatcher执行connect方法
重点
AMS在转发数据时有两个要点,类似的模式也出现在ContentProvider中:
a. AMS通过IApplicationThread通知Service#bindService,Service通过publishService传递给AMS生成的Binder,并记录在AMS的ActiveService中,Service进程中的Service记录和ActiveService中的记录一一对应的依据是ServiceRecord。
a. AMS以ServiceRecord为单元维护LoadedApk.ServiceDispatcher中生成的IServiceConnection对象,Server端通过publishService中传递参数IBinder,并触发从ServiceRecord中查找待绑定的IServiceConnection列表,并执行回调。
android服务的原理,android service原理相关推荐
- android服务无法启动,Android服务无法启动(Android service would't start)
Android服务无法启动(Android service would't start) 我正在尝试在Android中实现简单的服务,但我无法统计基本服务. 这是我的主要课程: import java ...
- android服务应用场景,Android Service的使用介绍
简介 Service是Android应用程序中的一个组件,与用户不进行交互,可以长期的执行在后台.当新建一个服务的时候需要在AndroidManifest.xml文件中进行声明.服务可以通过Conte ...
- android服务开启线程,android之service与intentService的不同
不知道大家有没有和我一样,以前做项目或者练习的时候一直都是用Service来处理后台耗时操作,却很少注意到还有个IntentService,前段时间准备面试的时候看到了一篇关于IntentServic ...
- android服务常驻内存,android service常驻内存的一点思考
我们总是不想自己的Android service被系统清理,以前时候大家最常用的办法就是在JNI里面fork出子进程,然后监视 service进程状态,被系统杀死了就重启它. 我分别在android4 ...
- android 服务自动结束,Android服务自动停止
我正在制作一个带有闹钟功能的应用程序.我正在使用这种服务,不断检查设备的当前时间与我的数据库中的时间.Android服务自动停止 我的问题是,如果应用程序从后台删除或设备是rebooted,此serv ...
- android服务下载apk,Android 一个简单的版本更新下载apk小示例
一.简介: 1.运用 okhttp + notification 通知栏带进度的下载apk,下载完毕后并自动安装,如果用户取消可在通知栏点击安装,点击一次通知栏移除,同时支持自动静默下载(后台默默下载 ...
- android服务下载apk,android下载apk并安装
1.设置权限 2.业务代码 package com.example.esri.app04.network; import android.app.ProgressDialog; import andr ...
- android服务拍视频,Android仿微信拍摄、录制视频,以及视频播放(基于JCameraView和GSYVideoPlayer)...
本项目使用Androidstudio开发工具 引入权限 引入依赖 //视频录制 implementation 'cjt.library.wheel:camera:1.1.9' //视频播放 api(' ...
- android系统自带的Service原理与使用
1. 说明 android的后台运行在很多service,它们在系统启动时被SystemServer开启,支持系统的正常工作,比如 MountService监听是否有SD卡安装及移除,Clipboar ...
- android服务自动重启,安卓service关闭后怎么自动重启
满意答案 首先申明service关闭有两种情况: 1.程序进入后台,系统可能会销毁应用,可以理解为android端监听推送消息的服务在启动后是一直在后台运行的,但是当内存不足时,或者第三方应用清理内存 ...
最新文章
- Pandas 中的 concat 函数
- React学习笔记2---生命周期
- statsmodels 笔记:seasonal_decompose 时间序列分解
- [渝粤教育] 武汉理工大学 刑法 参考 资料
- php 怎么查看原生方法源码_你的2020搜索账单地址入口 你的2020搜索账单怎么查看查看方法...
- matlab中的relop,MINP混合整数非线性规划问题求解(MATLAB OPTI toolbox)
- apache的rewrite规则来实现URL末尾是否带斜杠
- t-sql还原数据库_如何更新T-SQL工具箱数据库
- C#模拟GetPOST提交表单(一)--HttpWebRequest以及HttpWebResponse --WebClient,restsharp
- matlab距离平方和公式推导,求助高手,用matlab求两幅图像平方和再开根号公式怎样表达?...
- mysql大于小于索引问题
- Segment Routing入门
- java翻译后的文件扩展名_Java语言的源程序翻译成字节码之后的扩展名是.______。(填英文,小写)...
- 这 6 款在线 PDF 转换工具,得试试
- android user-agent iso-8859-1,微信大众,平台消息接口开辟(31)微信浏览器HTTP_USER_AGENT断定...
- 【无标题】2022年施工员-设备方向-通用基础(施工员)考试模拟100题及模拟考试
- GAN GAN Inversion
- PASA 全球aleo节点教程(pasa+aleo社区分享)
- 使用Python,提取视频文件中的音频
- 【黑金原创教程】【Modelsim】【第六章】结束就是开始