Android Guide Dev 之Processes and Threads

【信息科学与工程学】【数据中心】第三十五篇 云计算数据中心的学科知识04 编号学科(课程)核心知识点在云计算/云存储/云网络/云安全/云MaaS中的作用代表教材/资料/论文 + 数学方程式列表工业界应用D1421​云原生数据库:TiDB​HTAP(混合事务/分析处理)、分布式SQL、水平扩展、强一致(Raft)、自动故障恢复、与MySQL兼容、TiFlash列式引擎提供弹性扩展的分布式数据库;支撑高并发在线交易与实时分析教材:《TiDB in Action》PingCAP(2020) 论文:《TiDB: A Raft-based HTAP Database》(2017) 阅读详情
 

 Processes and Threads

When an application component starts and the application does not have any other components running, the Android system starts a new Linux process for the application with a single thread of execution. By default, all components of the same application run in the same process and thread (called the "main" thread). If an application component starts and there already exists a process for that application (because another component from the application exists), then the component is started within that process and uses the same thread of execution. However, you can arrange for different components in your application to run in separate processes, and you can create additional threads for any process.

This document discusses how processes and threads work in an Android application

Processes

By default, all components of the same application run in the same process and most applications should not change this. However, if you find that you need to control which process a certain component belongs to, you can do so in the manifest file.

The manifest entry for each type of component element—<activity>, <service>, <receiver>, and <provider>—supports an android:process attribute that can specify a process in which that component should run. You can set this attribute so that each component runs in its own process or so that some components share a process while others do not. You can also set android:process so that components of different applications run in the same process—provided that the applications share the same Linux user ID and are signed with the same certificates.

The <application> element also supports an android:process attribute, to set a default value that applies to all components.

Android might decide to shut down a process at some point, when memory is low and required by other processes that are more immediately serving the user. Application components running in the process that's killed are consequently destroyed. A process is started again for those components when there's again work for them to do.

When deciding which processes to kill, the Android system weighs their relative importance to the user. For example, it more readily shuts down a process hosting activities that are no longer visible on screen, compared to a process hosting visible activities. The decision whether to terminate a process, therefore, depends on the state of the components running in that process. The rules used to decide which processes to terminate is discussed below.

Process lifecycle

The Android system tries to maintain an application process for as long as possible, but eventually needs to remove old processes to reclaim memory for new or more important processes. To determine which processes to keep and which to kill, the system places each process into an "importance hierarchy" based on the components running in the process and the state of those components. Processes with the lowest importance are eliminated first, then those with the next lowest importance, and so on, as necessary to recover system resources.

There are five levels in the importance hierarchy. The following list presents the different types of processes in order of importance (the first process is most important and is killed last):

  1. Foreground process

    A process that is required for what the user is currently doing. A process is considered to be in the foreground if any of the following conditions are true:

    Generally, only a few foreground processes exist at any given time. They are killed only as a last resort—if memory is so low that they cannot all continue to run. Generally, at that point, the device has reached a memory paging state, so killing some foreground processes is required to keep the user interface responsive.

  2. Visible process

    A process that doesn't have any foreground components, but still can affect what the user sees on screen. A process is considered to be visible if either of the following conditions are true:

    • It hosts an Activity that is not in the foreground, but is still visible to the user (its onPause() method has been called). This might occur, for example, if the foreground activity started a dialog, which allows the previous activity to be seen behind it.
    • It hosts a Service that's bound to a visible (or foreground) activity.

    A visible process is considered extremely important and will not be killed unless doing so is required to keep all foreground processes running.

  3. Service process

    A process that is running a service that has been started with the startService() method and does not fall into either of the two higher categories. Although service processes are not directly tied to anything the user sees, they are generally doing things that the user cares about (such as playing music in the background or downloading data on the network), so the system keeps them running unless there's not enough memory to retain them along with all foreground and visible processes.

  4. Background process

    A process holding an activity that's not currently visible to the user (the activity's onStop() method has been called). These processes have no direct impact on the user experience, and the system can kill them at any time to reclaim memory for a foreground, visible, or service process. Usually there are many background processes running, so they are kept in an LRU (least recently used) list to ensure that the process with the activity that was most recently seen by the user is the last to be killed. If an activity implements its lifecycle methods correctly, and saves its current state, killing its process will not have a visible effect on the user experience, because when the user navigates back to the activity, the activity restores all of its visible state. See the Activities document for information about saving and restoring state.

  5. Empty process

    A process that doesn't hold any active application components. The only reason to keep this kind of process alive is for caching purposes, to improve startup time the next time a component needs to run in it. The system often kills these processes in order to balance overall system resources between process caches and the underlying kernel caches.

Threads

When an application is launched, the system creates a thread of execution for the application, called "main." This thread is very important because it is in charge of dispatching events to the appropriate user interface widgets, including drawing events. It is also the thread in which your application interacts with components from the Android UI toolkit (components from the android.widget and android.view packages). As such, the main thread is also sometimes called the UI thread.

The system does not create a separate thread for each instance of a component. All components that run in the same process are instantiated in the UI thread, and system calls to each component are dispatched from that thread. Consequently, methods that respond to system callbacks (such as onKeyDown() to report user actions or a lifecycle callback method) always run in the UI thread of the process.

For instance, when the user touches a button on the screen, your app's UI thread dispatches the touch event to the widget, which in turn sets its pressed state and posts an invalidate request to the event queue. The UI thread dequeues the request and notifies the widget that it should redraw itself.

When your app performs intensive work in response to user interaction, this single thread model can yield poor performance unless you implement your application properly. Specifically, if everything is happening in the UI thread, performing long operations such as network access or database queries will block the whole UI. When the thread is blocked, no events can be dispatched, including drawing events. From the user's perspective, the application appears to hang. Even worse, if the UI thread is blocked for more than a few seconds (about 5 seconds currently) the user is presented with the infamous "application not responding" (ANR) dialog. The user might then decide to quit your application and uninstall it if they are unhappy.

Additionally, the Andoid UI toolkit is not thread-safe. So, you must not manipulate your UI from a worker thread—you must do all manipulation to your user interface from the UI thread. Thus, there are simply two rules to Android's single thread model:

  1. Do not block the UI thread
  2. Do not access the Android UI toolkit from outside the UI thread

Worker threads

Because of the single thread model described above, it's vital to the responsiveness of your application's UI that you do not block the UI thread. If you have operations to perform that are not instantaneous, you should make sure to do them in separate threads ("background" or "worker" threads).

For example, below is some code for a click listener that downloads an image from a separate thread and displays it in an ImageView:

public void onClick(View v) {
    new Thread(new Runnable() {
        public void run() {
            Bitmap b = loadImageFromNetwork("http://example.com/image.png");
            mImageView.setImageBitmap(b);
        }
    }).start();
}

At first, this seems to work fine, because it creates a new thread to handle the network operation. However, it violates the second rule of the single-threaded model: do not access the Android UI toolkit from outside the UI thread—this sample modifies the ImageView from the worker thread instead of the UI thread. This can result in undefined and unexpected behavior, which can be difficult and time-consuming to track down.

To fix this problem, Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help:

For example, you can fix the above code by using the View.post(Runnable) method:

public void onClick(View v) {
    new Thread(new Runnable() {
        public void run() {
            final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png");
            mImageView.post(new Runnable() {
                public void run() {
                    mImageView.setImageBitmap(bitmap);
                }
            });
        }
    }).start();
}

Now this implementation is thread-safe: the network operation is done from a separate thread while the ImageView is manipulated from the UI thread.

However, as the complexity of the operation grows, this kind of code can get complicated and difficult to maintain. To handle more complex interactions with a worker thread, you might consider using a Handler in your worker thread, to process messages delivered from the UI thread. Perhaps the best solution, though, is to extend the AsyncTask class, which simplifies the execution of worker thread tasks that need to interact with the UI.

Using AsyncTask

AsyncTask allows you to perform asynchronous work on your user interface. It performs the blocking operations in a worker thread and then publishes the results on the UI thread, without requiring you to handle threads and/or handlers yourself.

To use it, you must subclass AsyncTask and implement the doInBackground() callback method, which runs in a pool of background threads. To update your UI, you should implement onPostExecute(), which delivers the result from doInBackground() and runs in the UI thread, so you can safely update your UI. You can then run the task by calling execute() from the UI thread.

For example, you can implement the previous example using AsyncTask this way:

public void onClick(View v) {
    new DownloadImageTask().execute("http://example.com/image.png");
}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    /** The system calls this to perform work in a worker thread and
      * delivers it the parameters given to AsyncTask.execute() */
    protected Bitmap doInBackground(String... urls) {
        return loadImageFromNetwork(urls[0]);
    }
    
    /** The system calls this to perform work in the UI thread and delivers
      * the result from doInBackground() */
    protected void onPostExecute(Bitmap result) {
        mImageView.setImageBitmap(result);
    }
}

Now the UI is safe and the code is simpler, because it separates the work into the part that should be done on a worker thread and the part that should be done on the UI thread.

You should read the AsyncTask reference for a full understanding on how to use this class, but here is a quick overview of how it works:

Caution: Another problem you might encounter when using a worker thread is unexpected restarts in your activity due to a runtime configuration change (such as when the user changes the screen orientation), which may destroy your worker thread. To see how you can persist your task during one of these restarts and how to properly cancel the task when the activity is destroyed, see the source code for the Shelves sample application.

Thread-safe methods

In some situations, the methods you implement might be called from more than one thread, and therefore must be written to be thread-safe.

This is primarily true for methods that can be called remotely—such as methods in a bound service. When a call on a method implemented in an IBinder originates in the same process in which the IBinder is running, the method is executed in the caller's thread. However, when the call originates in another process, the method is executed in a thread chosen from a pool of threads that the system maintains in the same process as the IBinder (it's not executed in the UI thread of the process). For example, whereas a service's onBind() method would be called from the UI thread of the service's process, methods implemented in the object that onBind() returns (for example, a subclass that implements RPC methods) would be called from threads in the pool. Because a service can have more than one client, more than one pool thread can engage the same IBinder method at the same time. IBinder methods must, therefore, be implemented to be thread-safe.

Similarly, a content provider can receive data requests that originate in other processes. Although the ContentResolver and ContentProvider classes hide the details of how the interprocess communication is managed, ContentProvider methods that respond to those requests—the methods query(), insert(), delete(), update(), and getType()—are called from a pool of threads in the content provider's process, not the UI thread for the process. Because these methods might be called from any number of threads at the same time, they too must be implemented to be thread-safe.

 

Qt Location实战:5分钟搞定地图插件切换与卫星图源加载(附完整代码) 本文是Qt Location开发系列教程的实战指南,详细讲解如何在Qt应用中快速实现地图插件(如Esri、OSM、MapboxGL)的动态切换与卫星图源的加载。通过清晰的代码示例,帮助开发者理解插件机制,解决常见配置问题,并在5分钟内构建出具备交互式地图切换功能的应用程序。 阅读详情

相关推荐

CDO批量处理nc文件:5分钟搞定CMIP6数据双线性插值(附完整代码)

本文详细介绍了如何使用CDO工具链中的`remapbil`命令,快速实现CMIP6数据的批量双线性插值处理。通过环境配置、核心操作步骤、高级优化技巧及典型报错解决方案,帮助科研人员高效处理大规模nc文件,显著提升气象数据处理效率。

weixin_29267307的博客 292

Android developer dev guide 应用程序基础之processes and threads

2010-05-09 19:41:09   第三部分是线程和进程的内容,内容比较少,熟悉操作系统的人可以不用看了 电子版已经上传,http://download.youkuaiyun.com/source/2333509       Android 开发者 应用程序基础   ——————————————————————————————

521

Hodgkin-Huxley Model

介绍了经典的动力学模型:HH Model

weixin_73557167的博客 2474

adb shell am broadcast

使用am发启广播adb shell am broadcast -a android.provider.Telephony.SECRET_CODE  -d android_secret_code://28346            广播端:        import stati

jackie_gnu的专栏 6123

Netty源码分析系列之writeAndFlush()下

write()只会将数据只是发送到了ChannelOutboundBuffer 缓冲区中,还没有被发送到操作系统的套接字中只有当调用了 flush()方法后,才会真正将数据发送到套接字中。那么 flush()方法的源码又是如何执行的呢?

天堂的博客 1572

PyTorch模型生产部署:ONNX/Triton导出与高可用架构实战

机器学习模型部署本质是训练环境与生产环境之间的运行时契约建立过程,涉及序列化协议、推理引擎兼容性、动态批处理及资源隔离等核心问题。ONNX凭借标准化算子集和跨框架支持,成为平衡兼容性、性能与可维护性的首选导出格式;Triton Inference Server则通过原生多框架支持、动态batching和热加载能力,显著提升GPU利用率与服务SLA保障水平。在金融风控、电商推荐等高要求场景中,基于ONNX+Triton+K8s的分层架构可稳定支撑千级QPS与毫秒级P95延迟,同时满足模型热更新、可观测性与版本

weixin_33857679的博客 447

aapt

Android Asset Packaging ToolUsage: aapt l[ist] [-v] [-a] file.{zip,jar,apk}   List contents of Zip-compatible archive. aapt d[ump] [--values] WHAT file.{apk} [asset [asset ...]]   badging         

jackie_gnu的专栏 3867

基于Simulink的PR(比例谐振)控制器在单相整流中的应用

本文详细介绍了基于Simulink的单相整流系统中PR(比例谐振)控制器的设计与实现方法。首先阐述了PR控制器相较于传统PI控制器的优势,能够有效消除交流信号跟踪中的稳态误差。接着系统讲解了PR控制器的传递函数原理、实用型设计(带带宽)及参数整定方法。通过Simulink建模步骤,包括主功率电路搭建、电压外环PI设计、电流指令生成、PR控制器实现(推荐MATLAB Function方法)和SPWM调制等关键环节。仿真对比显示PR控制在电流跟踪精度(THD仅1.9%)、功率因数(0.998)和动态响应(突变恢

amy_mhd的博客 689

在非锁屏的任意状态下监测HOME键

定义BroadcastReceiver 用于接收 action: android.intent.action.CLOSE_SYSTEM_DIALOGSpublic class HomeKeyPressedReceiver extends BroadcastReceiver { private static final String TAG = "TestReceiver"; pri

jackie_gnu的专栏 3339

uniapp(全端兼容) - 最新详细实现双色球开奖走势图功能组件,uni-app红球走势图/蓝球走势图,解决双色球 “蓝球连线“ 问题,双色球效果及用线连接每个号码详细教程(同样适用于彩票开奖走势图

uni-app,双色球,安卓app,苹果app,微信小程序,移动端,H5网页,手机网站,微信小程序、支付宝小程序,手机app端,nvue,红球走势,蓝球走势,连线,uniapp(vue):js实现双色球开奖走势图带连线,vue2,vue3,uniApp双色球组件插件,uniapp如何实现双色球走势图和连线,彩票走势图,前端 Vue实现彩票走势图,详细示例,走势图,彩票项目,绘制股票走势图,前端 JS实现彩票开奖走势图 连线,Uniapp有没有双色球的页面代码,红球蓝球的走势图如何做,双色球红球和值尾走势图,

✅ 精选推荐文章 3344

AI辅助Android开发:从传统到智能化的技术演进

AI辅助开发的核心在于利用算法模型自动化或优化传统任务。在Android开发中,AI可应用于需求分析、设计、编码、测试和维护各阶段。需求分析:AI工具如基于NLP的模型(例如GPT系列)可解析用户需求文档,自动生成用户故事和原型设计。假设产品需求为“开发一个航班查询应用”,AI能提取关键词,输出UML图或伪代码。代码生成:使用AI代码助手(如GitHub Copilot),工程师输入自然语言描述,AI生成Java/Kotlin代码片段。

郑伟强dev的专栏 137

动态库so打包到android apk

编译libjnisimple.so Android/development/samples/SimpleJNI/jni/Android.mk# This makefile supplies the rules for building a library of JNI code

jackie_gnu的专栏 3019

基于STM32L4XX、HAL库的STS40-CD1B-R3温度传感器 驱动程序设计

/ HAL库需要左移一位。// 每2秒读取一次。// 等待测量完成 - 高精度模式大约需要15ms。// 执行软复位确保传感器处于已知状态。温度测量范围:-40°C ~ +125°C。湿度测量范围:0% ~ 100% RH。// 复位后需要等待至少1ms。// 初始化STS40传感器。// 读取温湿度数据。// 转换原始数据为实际值。// 发送读取序列号命令。// 读取序列号数据。湿度精度:±1.5% RH。

zhusl6688的博客 287

dex-preopt,使用方法

# # Usage: dex-preopt [options] path/to/input.jar path/to/output.odex # # This tool runs a host build of dalvikvm in order to preoptimize dex # files that will be run on a device . # The input m

jackie_gnu的专栏 2927

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

dexdump反编译Android程序

反编译Android程序目前没有什么好的方法,但是在Android Emulator中可以找到一个名为dexdump(在Android SDK的Tools目标下)的程序,通过dexdump可以查看出apk文件中的dex执行情况,ophone8.com粗略分析出原始java代码是什么样的和Dot Net中的Reflector很像。 android编译器生成的java class相关内容都放到了d

jackie_gnu的专栏 2225

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

Android Java 调用linux 命令

方法1: copy from RootExplorer怎么样获取root权限的 ProcessBuilder pb = new ProcessBuilder("/system/bin/sh"); //java.lang.ProcessBuilder: Creates opera

jackie_gnu的专栏 2024

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

adb shell dumpsys

# adb shell dumpsys media.camera -v 1Client (0x18fd0) PID: 1437QualcommCameraHardware::dumpmMsgEnabled (29)preview width(640) x height (480)

jackie_gnu的专栏 1988

Android中静态jar库

如何编译也static jar library. 17 # Note: the source code is in java/, not src/, because this code is also part of 18 # the framework library, and build/core/pathmap.mk expects a java/ subdirectory.

jackie_gnu的专栏 1453

在Eclipse中编译apk时,把其他的apk做为库文件导入

用Eclipse进行编译apk时,有时需要把其他的apk做为库导入, 方法如下: 1.创建做为库导入的apk项目, 与正常的apk没有什么区别,除了在default.properties文件中添加定义android.library=true,标识此apk做为库导出. 2.创建apk导入之前创建的库文件.    properties->android->Library->Add... , 你将

jackie_gnu的专栏 1383

签名apk

1.生成keystore  生成密钥:keytool -genkey -alias bst.keystore -keyalg RSA -validity 20000 -keystore bst.keystore 给APK签名:jarsigner -verbose -keystore bst.keystore -signedjar WiMo_signed.apk WiMo-system.ap

jackie_gnu的专栏 1289

加快Android编译速度

# # Include all of the makefiles in the system # # Can't use first-makefiles-under here because # --mindepth=2 makes the prunes not work

jackie_gnu的专栏 1276

InputFilter

<br />1. InputFilter限制大写<br />InputFilter smallFilter = new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++) {

jackie_gnu的专栏 1225

如何查找内存泄漏

安装eclipse内存分析插件 www.eclipse.org/mat但是,有时候会安装不上!可以直接下载mat, 直接使用exe,当然,不如eclipse方便。 1,进入adb shell, ps想要dump内存堆栈的进程,记录pidps命令,知道进程号app_34    1231   97    259556 26172 ffffffff afd0eb18 S com.andr

jackie_gnu的专栏 1012

aapt tool

<br />Android Asset Packaging Tool(aapt)<br /> <br />aapt l[ist] [-v] [-a] file.{zip,jar,apk}<br />  List contents of Zip-compatible archive.<br />aapt d[ump] [--values] WHAT file.{apk} [asset [asset ...]]<br />  badging          Print the label and icon f

jackie_gnu的专栏 953

Android 14+ 模拟器抓包实录:把 Burp CA 装成系统 CA,让 targetSdk≥34 的 App 乖乖解密

本文记录了在 Android 14+ 环境下,通过将 Burp CA 安装为系统信任锚,成功抓取 targetSdk=35 App 的 HTTPS 明文流量的完整实操过程。针对“浏览器可用、App 不可用”的典型现象,精准识别出根本原因是系统级证书信任策略变更(用户安装的 CA 被屏蔽),而非 SSL Pinning。仅通过 adb 命令将 CA 推送至系统证书存储并重启生效,无需 Frida、Objection 或修改 APK,实现零侵入解密。全文命令均基于 Windows + MuMu 模拟器环境实测通

JIANqiao19931029的博客 341

具身智能 2026:启元人形机器人开发者生态的“安卓时刻”来了吗

一个贯穿全文的问题:人形机器人开发者生态,是否正从「封闭垂直」走向「开源平台化」?本文以开源底座的公开数据为标尺,盘点 SDK、URDF、仿真与技能分发的开放程度,并落回启元机器人的开源路径。所有关键数据均标注来源,文末附社区与学堂链接。

在北风吹起的时候加入我们的队伍 在秋雨到来的时候成为彼此的温暖 744
上一篇: Details on individual partitions
下一篇: Building Custom Components
jackie_gnu
博客等级 码龄16年 3粉丝 114原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值