首页 文章 精选 留言 我的

精选列表

搜索[鸿蒙课程],共8152篇文章
优秀的个人博客,低调大师

Android官方开发文档Training系列课程中文版:线程执行操作之创建多线程管理器

原文地址:http://android.xsoftlab.net/training/multiple-threads/create-threadpool.html 上节课我们学习了如何定义一个任务。如果只是执行单次任务,那么刚刚所学的已经基本满足要求了。如果需要针对不同的数据执行同种任务,并且需要同一时间只能执行一项任务,那么IntentService可能会适合你。如果要使任务随着资源的可用而执行,或者同一时间需要运行多个任务,那么就需要专门管理这些线程了。Android系统为此提供了一个类,那就是传说中的ThreadPoolExecutor。它可以在线程可用时自动运行队列中的任务。如果要运行一个任务,只需要将任务添加到队列中即可。 ThreadPoolExecutor允许多个线程同时进行,所以应当确保代码是线程安全的。要确保可能会被多个线程访问到的变量被放在同步代码块中。这种方法可以防止一个线程正在读取一个变量的值,而另一个变量正在对这个变量写入新值的现象出现。通常情况下,这种现象会发生在静态变量中,但是也会发生在单例对象上。 定义线程池类 在该类内实例化一个ThreadPoolExecutor对象,并在该类内执行以下工作: 对线程池对象使用静态变量引用 在APP内通常只需要一个线程池对象的存在:为了对CPU资源或网络资源有一个单一的控制。如果含有不同的Runnable类型,你可能希望对每种类型都创建一个单独线程池,但是每种类型都还是单例类型。在这里的例子中,可以添加以下代码作为全局属性声明。 public class PhotoManager { ... static { ... // Creates a single static instance of PhotoManager sInstance = new PhotoManager(); } ... 使用私有构造方法: 私有的构造方法可以确保该类只有一个对象存在。 public class PhotoManager { ... /** * Constructs the work queues and thread pools used to download * and decode images. Because the constructor is marked private, * it's unavailable to other classes, even in the same package. */ private PhotoManager() { ... } 调用线程池的相关方法启动任务: 在线程池类内定义一个可以向线程池队列中添加任务的方法。 public class PhotoManager { ... // Called by the PhotoView to get a photo static public PhotoTask startDownload( PhotoView imageView, boolean cacheFlag) { ... // Adds a download task to the thread pool for execution sInstance. mDownloadThreadPool. execute(downloadTask.getHTTPDownloadRunnable()); ... } 在构造方法中实例化一个Handler对象,并将其连接到UI线程:Handler允许安全的调用比如View这种UI对象。大多数的UI对象只允许被UI线程访问。 private PhotoManager() { ... // Defines a Handler object that's attached to the UI thread mHandler = new Handler(Looper.getMainLooper()) { /* * handleMessage() defines the operations to perform when * the Handler receives a new Message to process. */ @Override public void handleMessage(Message inputMessage) { ... } ... } } 确定线程池参数 如果要实例化ThreadPoolExecutor对象,需要用到以下值: 线程池的初始值以及最大值: 线程数量的初始值用于指定池子的初始大小,最大值代表了该线程池所允许开放的最大并发数量。线程池中的线程数量取决于设备的可用核心数。这个值与当前的设备颇有关系: public class PhotoManager { ... /* * Gets the number of available cores * (not always the same as the maximum number of cores) */ private static int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors(); } 这个值可能不能够反映设备的物理核心数量;在一些设备上,核心是否可用取决于系统是否加载。对于这些设备,availableProcessors()返回了当前的活跃核心数量,这个值可能要比真实的总核心数要低。 存活时长及单位 线程在被关闭之间的闲置时长。这个时长由时间单元值负责解释,这些时间单位常量被定义在类TimeUnit中。 任务队列 一个持有Runnable对象的队列。为了启动线程中的执行代码,线程池管理器采用了先进先出的管理原则。在创建线程池之前需要提供一个这样的队列,使用任何实现了BlockingQueue接口的类皆可。为了匹配到APP的要求,你可以选择适当的队列实现;学习更多它们的相关知识,请参见ThreadPoolExecutor的描述文档。这里的使用了LinkedBlockingQueue: public class PhotoManager { ... private PhotoManager() { ... // A queue of Runnables private final BlockingQueue<Runnable> mDecodeWorkQueue; ... // Instantiates the queue of Runnables as a LinkedBlockingQueue mDecodeWorkQueue = new LinkedBlockingQueue<Runnable>(); ... } ... } 线程池创建 创建一个线程池,只需调用ThreadPoolExecutor()实例化一个线程池管理器就好。它会创建并管理一组线程。因为线程池大小的初始值与最大值是相同的,所以ThreadPoolExecutor()会在初始化的时候创建出所指定的线程数量: private PhotoManager() { ... // Sets the amount of time an idle thread waits before terminating private static final int KEEP_ALIVE_TIME = 1; // Sets the Time Unit to seconds private static final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS; // Creates a thread pool manager mDecodeThreadPool = new ThreadPoolExecutor( NUMBER_OF_CORES, // Initial pool size NUMBER_OF_CORES, // Max pool size KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDecodeWorkQueue); }

优秀的个人博客,低调大师

Android官方开发文档Training系列课程中文版:后台服务之响应IntentService的处理结果

原文地址:https://developer.android.com/training/run-background-service/report-status.html 这节课主要学习如何将IntentService中的执行结果返回给请求点。一种推荐的方式就是使用 LocalBroadcastManager来实现,它会将所广播的Intent限制在APP内部。 发送IntentService的处理结果 为了可以将IntentService的处理结果发送给其它组件,首先需要创建一个Intent对象,并将执行结果放入该Intent内。 接下来要做的就是:将刚才创建好的Intent通过LocalBroadcastManager.sendBroadcast()发送出去。但凡是对该Intent注册了的,那么发送该Intent都会收到结果。可以通过getInstance()获取LocalBroadcastManager的实例。 例子如下: public final class Constants { ... // Defines a custom Intent action public static final String BROADCAST_ACTION = "com.example.android.threadsample.BROADCAST"; ... // Defines the key for the status "extra" in an Intent public static final String EXTENDED_DATA_STATUS = "com.example.android.threadsample.STATUS"; ... } public class RSSPullService extends IntentService { ... /* * Creates a new Intent containing a Uri object * BROADCAST_ACTION is a custom Intent action */ Intent localIntent = new Intent(Constants.BROADCAST_ACTION) // Puts the status into the Intent .putExtra(Constants.EXTENDED_DATA_STATUS, status); // Broadcasts the Intent to receivers in this app. LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent); ... } 下一步就是如何处理接收到的Intent对象了。 接收IntentService的处理结果 如果需要接收广播出来的Intent,那么就需要用到BroadcastReceiver了。在BroadcastReceiver的实现类中重写onReceive()方法。当LocalBroadcastManager将相应的Intent对象广播出来后,那么该方法就会被自动回调。 举个例子: // Broadcast receiver for receiving status updates from the IntentService private class ResponseReceiver extends BroadcastReceiver { // Prevents instantiation private DownloadStateReceiver() { } // Called when the BroadcastReceiver gets an Intent it's registered to receive @ public void onReceive(Context context, Intent intent) { ... /* * Handle Intents here. */ ... } } 一旦定义好了BroadcastReceiver,那么就可以为其定义指定的意图过滤器了。要做到这些,需要创建一个IntentFilter。下面的代码演示了如何定义一个过滤器: // Class that displays photos public class DisplayActivity extends FragmentActivity { ... public void onCreate(Bundle stateBundle) { ... super.onCreate(stateBundle); ... // The filter's action is BROADCAST_ACTION IntentFilter mStatusIntentFilter = new IntentFilter( Constants.BROADCAST_ACTION); // Adds a data filter for the HTTP scheme mStatusIntentFilter.addDataScheme("http"); 为了将BroadcastReceiver以及IntentFilter注册到系统,需要先获取LocalBroadcastManager的实例,然后再调用它的registerReceiver()方法。下面的代码演示了这个过程: // Instantiates a new DownloadStateReceiver DownloadStateReceiver mDownloadStateReceiver = new DownloadStateReceiver(); // Registers the DownloadStateReceiver and its intent filters LocalBroadcastManager.getInstance(this).registerReceiver( mDownloadStateReceiver, mStatusIntentFilter); ... BroadcastReceiver可以同时处理多种类型的Intent对象,这项特性可以为每种Action定义不同的代码,而不需要专门去定义BroadcastReceiver。为同一个BroadcastReceiver定义另外的IntentFilter,只需再创建一个IntentFilter,然后再次注册一下就好: /* * Instantiates a new action filter. * No data filter is needed. */ statusIntentFilter = new IntentFilter(Constants.ACTION_ZOOM_IMAGE); ... // Registers the receiver with the new filter LocalBroadcastManager.getInstance(getActivity()).registerReceiver( mDownloadStateReceiver, mIntentFilter); 发送广播Intent并不会启动或者恢复Activity。就算是APP处于挂起状态(处于后台)也同样会接收到Intent。如果APP处于挂起状态的话,有任务完成需要通知到用户,那么可以使用Notification做到。绝不要启动Activity来响应接收到的Intent广播。

优秀的个人博客,低调大师

[鸿蒙从零到一] HarmonyOS 冷启动瀑布图分析与关键路径裁剪实战

冷启动是用户对一个应用的第一印象。很多团队做启动优化时习惯"东砍一刀西砍一刀",删了几个初始化、加了个懒加载,数据却没什么变化。根本原因是:没有先拿到瀑布图,就没有关键路径,优化自然无的放矢。本文围绕 HarmonyOS 应用冷启动,讲清楚三件事:冷启动各阶段到底发生了什么、如何用 HiTrace / DevEco Profiler 拿到一张可信的瀑布图、以及如何据此裁剪关键路径并量化收益。

优秀的个人博客,低调大师

[鸿蒙从零到一] HarmonyOS 性能优化:启动、渲染与内存的系统治理

HarmonyOS 应用功能日趋丰富,性能问题已成为开发者无法回避的工程挑战。用户对应用的第一印象往往来自启动速度,而长期使用中的流畅感和稳定性则由渲染效率与内存健康度决定。本文聚焦三大核心性能维度:冷启动优化、ArkUI 渲染性能、内存管理与泄漏排查,结合 ArkTS 代码示例,系统梳理从问题发现到落地治理的完整路径。

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

WebStorm

WebStorm

WebStorm 是jetbrains公司旗下一款JavaScript 开发工具。目前已经被广大中国JS开发者誉为“Web前端开发神器”、“最强大的HTML5编辑器”、“最智能的JavaScript IDE”等。与IntelliJ IDEA同源,继承了IntelliJ IDEA强大的JS部分的功能。

用户登录
用户注册