android activity 管理器AMS----概述

AMS & WMS,应该是app端打交道最多的2个framwork层的service。

ActivityManagerService 是android提供给用于管理Activity运行状态的系统进程。

本系列共分3个部分,概述,ActivityStatck & Activiy Task.

一. AMS概述

首先AMS 是一个同我们开发的service非常相似的一个service,只不过它的作用是管理activity。

所以AMS是一个进程,并且当开机以后,它就常驻在系统里面,归ServiceManager调度。

而AMS启动后,它开始有一个线程监听处理客户的需求。

一下为android5.0 的代码:

\frameworks\base\services\java\com\android\server\SystemServera.java

private void startBootstrapServices() {
        // Wait for installd to finish starting up so that it has a chance to
        // create critical directories such as /data/user with the appropriate
        // permissions.  We need this to complete before we initialize other services.
        mInstaller = mSystemServiceManager.startService(Installer.class);

        // Activity manager runs the show.
        mActivityManagerService = mSystemServiceManager.startService(
                ActivityManagerService.Lifecycle.class).getService();
        mActivityManagerService.setSystemServiceManager(mSystemServiceManager);

        // Power manager needs to be started early because other services need it.
        // Native daemons may be watching for it to be registered so it must be ready
        // to handle incoming binder calls immediately (including being able to verify
        // the permissions for those calls).
        mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);

        // Now that the power manager has been started, let the activity manager
        // initialize power management features.
        mActivityManagerService.initPowerManagement();

        // Display manager is needed to provide display metrics before package manager
        // starts up.
        mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);

        // We need the default display before we can initialize the package manager.
        mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);

        // Only run "core" apps if we‘re encrypting the device.
        String cryptState = SystemProperties.get("vold.decrypt");
        if (ENCRYPTING_STATE.equals(cryptState)) {
            Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
            mOnlyCore = true;
        } else if (ENCRYPTED_STATE.equals(cryptState)) {
            Slog.w(TAG, "Device encrypted - only parsing core apps");
            mOnlyCore = true;
        }

        // Start the package manager.
        Slog.i(TAG, "Package Manager");
        mPackageManagerService = PackageManagerService.main(mSystemContext, mInstaller,
                mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
        mFirstBoot = mPackageManagerService.isFirstBoot();
        mPackageManager = mSystemContext.getPackageManager();

        Slog.i(TAG, "User Service");
        ServiceManager.addService(Context.USER_SERVICE, UserManagerService.getInstance());

        // Initialize attribute cache used to cache resources from packages.
        AttributeCache.init(mSystemContext);

        // Set up the Application instance for the system process and get started.
        mActivityManagerService.setSystemProcess();
    }

startBootstrapServices

可以看到AMS在这里启动。而这个函数startBootstrapServices是在run方法中运行。

public ActivityManagerService(Context systemContext) {
        mContext = systemContext;
        mFactoryTest = FactoryTest.getMode();
        mSystemThread = ActivityThread.currentActivityThread();

        Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());

        mHandlerThread = new ServiceThread(TAG,
                android.os.Process.THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
        mHandlerThread.start();
        mHandler = new MainHandler(mHandlerThread.getLooper());

        mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
                "foreground", BROADCAST_FG_TIMEOUT, false);
        mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
                "background", BROADCAST_BG_TIMEOUT, true);
        mBroadcastQueues[0] = mFgBroadcastQueue;
        mBroadcastQueues[1] = mBgBroadcastQueue;

        mServices = new ActiveServices(this);
        mProviderMap = new ProviderMap(this);

        // TODO: Move creation of battery stats service outside of activity manager service.
        File dataDir = Environment.getDataDirectory();
        File systemDir = new File(dataDir, "system");
        systemDir.mkdirs();
        mBatteryStatsService = new BatteryStatsService(systemDir, mHandler);
        mBatteryStatsService.getActiveStatistics().readLocked();
        mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
        mOnBattery = DEBUG_POWER ? true
                : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
        mBatteryStatsService.getActiveStatistics().setCallback(this);

        mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));

        mAppOpsService = new AppOpsService(new File(systemDir, "appops.xml"), mHandler);

        mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"));

        // User 0 is the first and only user that runs at boot.
        mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
        mUserLru.add(Integer.valueOf(0));
        updateStartedUserArrayLocked();

        GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
            ConfigurationInfo.GL_ES_VERSION_UNDEFINED);

        mConfiguration.setToDefaults();
        mConfiguration.setLocale(Locale.getDefault());

        mConfigurationSeq = mConfiguration.seq = 1;
        mProcessCpuTracker.init();

        mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
        mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
        mStackSupervisor = new ActivityStackSupervisor(this);
        mTaskPersister = new TaskPersister(systemDir, mStackSupervisor);

        mProcessCpuThread = new Thread("CpuTracker") {
            @Override
            public void run() {
                while (true) {
                    try {
                        try {
                            synchronized(this) {
                                final long now = SystemClock.uptimeMillis();
                                long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
                                long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
                                //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
                                //        + ", write delay=" + nextWriteDelay);
                                if (nextWriteDelay < nextCpuDelay) {
                                    nextCpuDelay = nextWriteDelay;
                                }
                                if (nextCpuDelay > 0) {
                                    mProcessCpuMutexFree.set(true);
                                    this.wait(nextCpuDelay);
                                }
                            }
                        } catch (InterruptedException e) {
                        }
                        updateCpuStatsNow();
                    } catch (Exception e) {
                        Slog.e(TAG, "Unexpected exception collecting process stats", e);
                    }
                }
            }
        };

        mLockToAppRequest = new LockToAppRequestDialog(mContext, this);

        Watchdog.getInstance().addMonitor(this);
        Watchdog.getInstance().addThread(mHandler);
    }

ActivityManagerService

        mStackSupervisor = new ActivityStackSupervisor(this);
        mTaskPersister = new TaskPersister(systemDir, mStackSupervisor);

这两句是ActivityStack & ActivityTask设置的地方。

public void setSystemProcess()就比较简单了,它不仅注册了自己一个server, 还注册了其他的server。

 ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
            ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
            ServiceManager.addService("meminfo", new MemBinder(this));
            ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
            ServiceManager.addService("dbinfo", new DbBinder(this));
            if (MONITOR_CPU_USAGE) {
                ServiceManager.addService("cpuinfo", new CpuBinder(this));
            }
            ServiceManager.addService("permission", new PermissionController(this));

二.Activit状态管理---ActivityStack

1.ActivityState

定义了如下状态:

状态变化图。

三:startActivity

[email protected]

[email protected]

[email protected]

[email protected]

[email protected]

这5个函数先后关系,就是上面的顺序。

    public final int startActivity(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle options) {
        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
            resultWho, requestCode, startFlags, profilerInfo, options,
            UserHandle.getCallingUserId());
    }

多了一个

UserHandle.getCallingUserId()

调用者的Userid值,通过bind机制获得的。

    @Override
    public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) {
        enforceNotIsolatedCaller("startActivity");
        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
                false, ALLOW_FULL_ONLY, "startActivity", null);
        // TODO: Switch to user app stacks here.
        return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
                resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
                profilerInfo, null, null, options, false, userId, null, null);
    }

enforceNotIsolatedCaller 的目的是确认当前用户是否属于被隔离的对象。


接下来是 startActivityMayWait

时间: 2024-08-03 18:29:26

android activity 管理器AMS----概述的相关文章

Android布局管理器-使用LinearLayout实现简单的登录窗口布局

场景 Android布局管理器-从实例入手学习相对布局管理器的使用: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/103838924 线性布局LinearLayout,分为水平和垂直线性布局. 实现效果如下 注: 博客: https://blog.csdn.net/badao_liumang_qizhi 关注公众号 霸道的程序猿 获取编程相关电子书.教程推送与免费下载. 实现 将activity修改为LinearLayout

Android第二节(view简介以及Android布局管理器),维维复习

布局管理器是指定View之间的排列方式的.view就是UI控件,下节课我会整理到,这里我们先讲布局,大布局在我看来就相当于一个房间,让view显示,就是说物品在房间的摆放规则. 一.View的简介 View ,一般都有TextView,EditText,Button,RadioButton,CheckBox,ImageView,ImageButton. ViewGroup,一般有LinearLayout,RelativeLayout,FrameLayout,Spinner,ListView,Gr

Android Activity管理类优化内存利器非常方便

项目开启的Activity越多,占的内存越多,我们是不是有时候想当我打开很多界面的时候,我们到底打开多少个Activity,OK现在你的难题解决了,只有把这个Activity管理类复制到你的项目当中,随时随地管理的你的Activity,让你成为内存的主导者!不要问我叫什么,请叫我雷锋!首先看看效果图: 代码献上: /** * 2014-6-7 上午10:40:16 */ package com.jiub.client.mobile.manager; import java.util.Stack;

Android布局管理器浅析

在Android应用开发中,为了更好地管理Android应用的用户界面里的各组件,Android提供了布局管理器来实现Android应用的图形用户界面平台无关性,其中所有布局管理器的父类为ViewGroup.一般来说,推荐使用布局管理器来管理组件的分布.大小,而不是直接设置组件位置和大小.在开发当中,最常用的方法是预先设置好容器边距(分布).大小,然后其包含的组件使用"fill_match"或"wrap_content"自动适应父容器即可. 一.LinearLayo

Android布局管理器(线性布局)

线性布局有LinearLayout类来代表,Android的线性布局和Swing的Box有点相似(他们都会将容器里面的组件一个接一个的排列起来),LinearLayout中,使用android:orientation属性控制布局是水平还是竖直布局(vertical水平,horizontal竖直) XML属性 相关方法 说明 android:baselineAligned setBaselineAligned(boolean) 该属性设置为false,将会阻止该布局管理器与它的子元素的基线对其 a

Android布局管理器(表格布局)

表格布局有TableLayout所代表,TableLayout继承了LinearLayout,因此他的本质依然是LinearLayout. 表格布局采用行.列的形式来进行管理,在使用的时候不需要声明多少行.多少列,而是通过添加TableRow.其他组件来控制表格的行数和列数. 每次向TableLayout添加一个TableRow,该TableRow就是一个表格行,同时TableRow也是容器,可以在其中不断的添加其他的组件,每添加一个子组件,该表格的列就增加一列 在表格布局管理器中,可以为单元格

Android布局管理器(贞布局)

贞布局有FrameLayout所代表,它直接继承了ViewGroup组建 贞布局为每个加入其中的组件创建一个空白区域(一帧),所以每个子组件占用一帧,这些贞都会根据gravity属性执行自动对齐 贞布局在游戏开发中使用较多 Xml属性 相关方法 说明 Android:foreground setForeground 设置该贞的前景图形 Android:foregroundGravity SetForegroundGavity 定义绘制前景图形的gravity属性 布局代码: <FrameLayo

Android布局管理器-从实例入手学习相对布局管理器的使用

场景 AndroidStudio跑起来第一个App时新手遇到的那些坑: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/103797243 使用相对布局RelativeLayout实现简单的登录提示的布局,效果如下 注: 博客: https://blog.csdn.net/badao_liumang_qizhi 关注公众号 霸道的程序猿 获取编程相关电子书.教程推送与免费下载. 实现 新建之后的默认页面布局为 将其修改为Rela

Android Activity 管理