草庐IT

android - 使用 FusedLocationProviderClient 进行位置更新会产生内存泄漏

coder 2023-12-05 原文

我不明白为什么这个非常简单的 Activity 会产生内存泄漏。

它遵循此处给出的指南:https://developer.android.com/training/location/receive-location-updates.html 和此处给出的示例代码:https://github.com/googlesamples/android-play-location/tree/master/LocationUpdates

我还注意到,如果我不重写 LocationCallback 类的 onLocationResult 方法,内存泄漏就会得到解决。 但在这种情况下,LocationCallback 就完全没用了。

感谢您的帮助!

public class TestLeaks extends Activity {
    private FusedLocationProviderClient mFusedLocationClient;   // Access to Fused Loc. Provider API
    private LocationRequest mLocationRequest;         // Stores parameters for requests to F.L.P.Api
    private LocationCallback mLocationCallback;                      // Callback for Location events

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_leaks);

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
                Location loc = locationResult.getLastLocation();
                ((TextView) findViewById(R.id.latitude)).setText(String.format(Locale.US, "%.6f", loc.getLatitude()));
                ((TextView) findViewById(R.id.longitude)).setText(String.format(Locale.US, "%.6f", loc.getLongitude()));
            }
        };

        mLocationRequest = new LocationRequest()
                .setInterval(5000)
                .setFastestInterval(2000)
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onResume() {
        super.onResume();
        mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
    }

    @Override
    protected void onPause() {
        super.onPause();
        mFusedLocationClient.removeLocationUpdates(mLocationCallback);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationCallback = null;
    }
}

这是 LeakCanary 关于检测到的内存泄漏的输出:

In it.myapp.app:1.0.4:10004.
* it.myapp.app.activities.TestLeaks has leaked:
* GC ROOT com.google.android.gms.internal.zzcfe.zzfus
* references com.google.android.gms.common.api.internal.zzci.zzful
* references com.google.android.gms.common.api.internal.zzck.zzfuk
* references it.myapp.app.activities.TestLeaks$1.this$0 (anonymous subclass of com.google.android.gms.location.LocationCallback)
* leaks it.myapp.app.activities.TestLeaks instance

* Retaining: 35 KB.
* Reference Key: 969b4256-81ff-4b01-b0d4-63e27e49b764
* Device: samsung samsung SM-G920F zerofltexx
* Android Version: 7.0 API: 24 LeakCanary: 1.5.4 74837f0
* Durations: watch=637463ms, gc=258ms, heap dump=2766ms, analysis=46757ms

* Details:
* Instance of com.google.android.gms.internal.zzcfe
|   static $classOverhead = byte[768]@317861889 (0x12f23001)
|   zzfus = com.google.android.gms.common.api.internal.zzci@318105032 (0x12f5e5c8)
|   mDescriptor = java.lang.String@317290744 (0x12e978f8)
|   mObject = 511599546432
|   mOwner = com.google.android.gms.internal.zzcfe@317359520 (0x12ea85a0)
|   shadow$_klass_ = com.google.android.gms.internal.zzcfe
|   shadow$_monitor_ = 0
* Instance of com.google.android.gms.common.api.internal.zzci
|   static $classOverhead = byte[648]@316776449 (0x12e1a001)
|   zzfuj = com.google.android.gms.common.api.internal.zzcj@317594368 (0x12ee1b00)
|   zzfuk = null
|   zzful = com.google.android.gms.common.api.internal.zzck@318185888 (0x12f721a0)
|   shadow$_klass_ = com.google.android.gms.common.api.internal.zzci
|   shadow$_monitor_ = 0
* Instance of com.google.android.gms.common.api.internal.zzck
|   static $classOverhead = byte[608]@316789761 (0x12e1d401)
|   zzfuk = it.myapp.app.activities.TestLeaks$1@318185648 (0x12f720b0)
|   zzfun = java.lang.String@317049344 (0x12e5ca00)
|   shadow$_klass_ = com.google.android.gms.common.api.internal.zzck
|   shadow$_monitor_ = 0
* Instance of it.myapp.app.activities.TestLeaks$1
|   static $classOverhead = byte[640]@316606465 (0x12df0801)
|   static serialVersionUID = -1641506329145588052
|   static $change = null
|   this$0 = it.myapp.app.activities.TestLeaks@317686496 (0x12ef82e0)
|   shadow$_klass_ = it.myapp.app.activities.TestLeaks$1
|   shadow$_monitor_ = -1897236332
* Instance of it.myapp.app.activities.TestLeaks
|   static $classOverhead = byte[4336]@316567553 (0x12de7001)
|   static serialVersionUID = 2740572635131010457
|   static $change = null
|   mFusedLocationClient = com.google.android.gms.location.FusedLocationProviderClient@317049680 (0x12e5cb50)
|   mLocationCallback = null
|   mLocationRequest = com.google.android.gms.location.LocationRequest@318159496 (0x12f6ba88)
|   mActionBar = null
|   mActionModeTypeStarting = 0
|   mActivityInfo = android.content.pm.ActivityInfo@317696896 (0x12efab80)
|   mActivityTransitionState = android.app.ActivityTransitionState@317736656 (0x12f046d0)
|   mAppLockCheckRunnable = android.app.Activity$1@318057504 (0x12f52c20)
|   mAppLockIsInMultiWindowMode = false
|   mApplication = it.myapp.app.CanaryLeak@315492064 (0x12ce06e0)
|   mCalled = true
|   mChangeCanvasToTranslucent = false
|   mChangingConfigurations = false
|   mComponent = android.content.ComponentName@318099536 (0x12f5d050)
|   mConfigChangeFlags = 0
|   mCurrentConfig = android.content.res.Configuration@317764560 (0x12f0b3d0)
|   mDecor = null
|   mDefaultKeyMode = 0
|   mDefaultKeySsb = null
|   mDestroyed = true
|   mDoReportFullyDrawn = false
|   mEatKeyUpEvent = false
|   mEmbeddedID = null
|   mEnableDefaultActionBarUp = false
|   mEnterTransitionListener = android.app.SharedElementCallback$1@1899179144 (0x71332c88)
|   mExitTransitionListener = android.app.SharedElementCallback$1@1899179144 (0x71332c88)
|   mFinished = true
|   mFlipfont = 0
|   mFragments = android.app.FragmentController@318057472 (0x12f52c00)
|   mHandler = android.os.Handler@317542688 (0x12ed5120)
|   mHasCurrentPermissionsRequest = false
|   mIdent = 165309401
|   mInstanceTracker = android.os.StrictMode$InstanceTracker@318057488 (0x12f52c10)
|   mInstrumentation = android.app.Instrumentation@315494968 (0x12ce1238)
|   mIntent = android.content.Intent@314929344 (0x12c570c0)
|   mLastNonConfigurationInstances = null
|   mMainThread = android.app.ActivityThread@315314736 (0x12cb5230)
|   mManagedCursors = java.util.ArrayList@318035832 (0x12f4d778)
|   mManagedDialogs = null
|   mMenuInflater = null
|   mParent = null
|   mPolicyManager = null
|   mReferrer = java.lang.String@314929856 (0x12c572c0)
|   mResultCode = 0
|   mResultData = null
|   mResumed = false
|   mScreenChangeListener = null
|   mSearchEvent = null
|   mSearchManager = null
|   mStartedActivity = false
|   mStopped = true
|   mTaskDescription = android.app.ActivityManager$TaskDescription@317542720 (0x12ed5140)
|   mTemporaryPause = false
|   mTitle = java.lang.String@315505152 (0x12ce3a00)
|   mTitleColor = 0
|   mTitleReady = true
|   mToken = android.os.BinderProxy@315387808 (0x12cc6fa0)
|   mTranslucentCallback = null
|   mUiThread = java.lang.Thread@2004343960 (0x7777dc98)
|   mVisibleBehind = false
|   mVisibleFromClient = true
|   mVisibleFromServer = true
|   mVoiceInteractor = null
|   mWindow = com.android.internal.policy.PhoneWindow@315451968 (0x12cd6a40)
|   mWindowAdded = true
|   mWindowManager = android.view.WindowManagerImpl@318034248 (0x12f4d148)
|   mInflater = com.android.internal.policy.PhoneLayoutInflater@316645632 (0x12dfa100)
|   mOverrideConfiguration = null
|   mResources = android.content.res.Resources@316047040 (0x12d67ec0)
|   mTheme = android.content.res.Resources$Theme@318057696 (0x12f52ce0)
|   mThemeResource = 2131820551
|   mBase = android.app.ContextImpl@316473008 (0x12dcfeb0)
|   shadow$_klass_ = it.myapp.app.activities.TestLeaks
|   shadow$_monitor_ = 1073742768
* Excluded Refs:
| Field: android.view.inputmethod.InputMethodManager.mNextServedView
| Field: android.view.inputmethod.InputMethodManager.mServedView
| Field: android.view.inputmethod.InputMethodManager.mServedInputConnection
| Field: android.view.textservice.SpellCheckerSession$1.this$0
| Field: com.samsung.android.content.clipboard.SemClipboardManager.mContext
| Field: com.samsung.android.emergencymode.SemEmergencyManager.mContext
| Field: android.view.Choreographer$FrameDisplayEventReceiver.mMessageQueue (always)
| Thread:FinalizerWatchdogDaemon (always)
| Thread:main (always)
| Thread:LeakCanary-Heap-Dump (always)
| Class:java.lang.ref.WeakReference (always)
| Class:java.lang.ref.SoftReference (always)
| Class:java.lang.ref.PhantomReference (always)
| Class:java.lang.ref.Finalizer (always)
| Class:java.lang.ref.FinalizerReference (always)

最佳答案

我遇到了同样的问题,然后是我的固定代码,如果需要的话给别人。

class WeakLocationCallback(locationCallback: LocationCallback) : LocationCallback() {

    private val weakLocationCallback = WeakReference<LocationCallback>(locationCallback)
    override fun onLocationResult(result: LocationResult) {
        super.onLocationResult(result)
        weakLocationCallback.get()?.onLocationResult(result)
    }
}  

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
        val locationRequest = LocationRequest()
        locationRequest.priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
        locationCallback = object : LocationCallback() {
            override fun onLocationResult(result: LocationResult) {
                super.onLocationResult(result)
                currentLocation = result.lastLocation
            }
        }
        val weakLocationCallback = WeakLocationCallback(locationCallback)
        fusedLocationClient.requestLocationUpdates(locationRequest, weakLocationCallback, Looper.myLooper())

关于android - 使用 FusedLocationProviderClient 进行位置更新会产生内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48675221/

有关android - 使用 FusedLocationProviderClient 进行位置更新会产生内存泄漏的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  5. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  6. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

    作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

  7. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  8. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  9. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  10. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

随机推荐