Bugly并非无所不能

发布于:2024-07-13 ⋅ 阅读:(124) ⋅ 点赞:(0)

在 iOS 应用因为内存占用过大而被系统 killed 的情况下,Bugly 以及大多数崩溃报告工具是无法捕获到这种类型的崩溃信息的。原因在于,当系统由于内存压力过大而终止应用时,是直接将应用进程杀死,不会触发常规的崩溃处理流程,如 NSUncaughtExceptionHandler 或信号处理器。因此,应用没有机会执行任何代码来记录和上报崩溃信息。

理解系统内存管理

iOS 系统有严格的内存管理机制,当设备内存紧张时,系统会逐步采取措施来释放内存资源:

  1. 发送内存警告:系统会向应用发送 UIApplicationDidReceiveMemoryWarningNotification 通知,提醒应用释放不必要的内存。
  2. 终止后台应用:如果内存警告未能有效缓解内存压力,系统会开始终止后台运行的应用。
  3. 终止前台应用:在极端情况下,如果内存压力依然存在,系统会直接终止内存占用过大的前台应用。

捕获内存警告

虽然 Bugly 无法捕获系统直接杀死应用的情况,但你可以通过监控内存警告来间接了解应用的内存使用情况,并采取相应措施以防止应用被系统杀死。

捕获内存警告通知

你可以在应用中监听 UIApplicationDidReceiveMemoryWarningNotification 通知,并在收到内存警告时记录相关信息:

import UIKit

class MemoryMonitor {
    init() {
        NotificationCenter.default.addObserver(self, selector: #selector(didReceiveMemoryWarning), name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
    }

    @objc private func didReceiveMemoryWarning() {
        // 记录内存警告日志
        print("Received memory warning")
        
        // 可以在这里上传内存警告信息到 Bugly
        // Bugly.log(level: .warn, content: "Received memory warning")
    }

    deinit {
        NotificationCenter.default.removeObserver(self, name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
    }
}
实时监控内存使用情况

你可以使用 task_vm_info API 来监控应用的内存使用情况,并在内存占用超过预设阈值时,记录日志或发送警告:

import Foundation
import MachO

func reportMemoryUsage() -> UInt64? {
    var taskInfo = mach_task_basic_info()
    var count = mach_msg_type_number_t(MemoryLayout<mach_task_basic_info>.size) / 4

    let kerr = withUnsafeMutablePointer(to: &taskInfo) {
        taskInfoPtr in
        taskInfoPtr.withMemoryRebound(to: integer_t.self, capacity: 1) {
            taskInfoIntPtr in
            task_info(mach_task_self_, task_flavor_t(MACH_TASK_BASIC_INFO), taskInfoIntPtr, &count)
        }
    }

    guard kerr == KERN_SUCCESS else {
        return nil
    }

    return taskInfo.resident_size
}

func monitorMemoryUsage() {
    let memoryThreshold: UInt64 = 200 * 1024 * 1024 // 设置内存阈值,例如 200MB
    if let memoryUsage = reportMemoryUsage(), memoryUsage > memoryThreshold {
        // 记录内存使用情况
        print("Memory usage is high: \(memoryUsage / 1024 / 1024) MB")
        
        // 可以在这里上传内存使用情况到 Bugly
        // Bugly.log(level: .warn, content: "Memory usage is high: \(memoryUsage / 1024 / 1024) MB")
    }
}

// 定期调用 monitorMemoryUsage 进行内存监控
Timer.scheduledTimer(withTimeInterval: 60.0, repeats: true) { _ in
    monitorMemoryUsage()
}

总结

虽然 Bugly 无法直接捕获应用因内存过大被系统杀死的情况,但通过监听内存警告通知和实时监控内存使用情况,可以间接了解应用的内存状态,并记录相关信息以便后续分析和优化。这样可以帮助你及时发现和解决内存问题,避免应用因内存过大被系统终止。


网站公告

今日签到

点亮在社区的每一天
去签到