obtainMessage的优点

本文深入探讨了Handler消息机制中obtainMessage方法的使用方式及其内存优势。通过对比new Message()的方式,obtainMessage能有效避免频繁创建新对象,从而达到节省内存的目的。文章通过实例演示了如何发送消息到目标处理器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Message msg = handler.obtainMessage();
Message msg = new Message();

从源码分析得到结论:obtainMessage不用创建新对象可以减少内存

Message mess = handler.obtainMessage();
			mess.sendToTarget();

### Android Handler `obtainMessage` Usage and Examples In the context of Android development, messages are a fundamental part of inter-thread communication within applications. The method `Handler.obtainMessage()` is used to retrieve an existing message from a recycled pool or create a new one when none exists in the pool. The primary advantage of using this approach over directly instantiating a Message object with its constructor lies in efficiency—reusing objects reduces garbage collection overhead by minimizing allocations[^1]. #### Basic Syntax To use `obtainMessage()`, simply call it on any instance of `Handler`. This will return either a pre-existing unused `Message` that was previously returned to the system via recycling mechanisms (such as calling recycle()) or instantiate a fresh one if no such items exist at present: ```java // Obtain a Message from handler's queue. Message msg = myHandler.obtainMessage(); ``` This basic invocation retrieves a blank slate upon which additional information can be set before dispatching back into circulation through sendMessage(), sendEmptyMessage(), etc., depending on requirements. #### Setting Arguments Within Messages Messages often carry data between threads; therefore setting arguments becomes necessary for meaningful exchanges. One common way involves utilizing what’s known as “what” field alongside arg1/arg2 integers provided specifically for lightweight payloads without requiring bundling complex structures like Parcels unless absolutely needed: ```java int operationCode = 1; msg.what = operationCode; // Optionally add more details using args fields msg.arg1 = someValue; msg.arg2 = anotherValue; ``` For larger datasets or non-primitive types, consider attaching Objects instead: ```java Bundle bundleData = new Bundle(); bundleData.putString("key", "value"); msg.setData(bundleData); ``` Or even simpler cases where only simple values need passing along: ```java String stringArg = "example"; msg.obj = stringArg; ``` Finally, after preparing your message accordingly, sending it off requires merely invoking appropriate methods available under Handlers API surface area: ```java myHandler.sendMessage(msg); // Dispatch immediately // Or schedule delayed delivery myHandler.sendMessageDelayed(msg, delayMillis); ``` Remember always to release resources properly once done processing received messages inside handleMessage(). Calling recycle() ensures these instances become eligible again for future reuse operations initiated by subsequent calls made against obtainMessage(): ```java @Override public void handleMessage(Message msg) { super.handleMessage(msg); int code = msg.what; switch(code){ case SOME_OPERATION_CODE: // Process specific task here... break; default: Log.w(TAG,"Unknown message type"); } // Always clean up afterwards! msg.recycle(); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值