小编Vas*_*chi的帖子

getSystemService()如何正常工作?

乍一看下面的代码中,mLocationManager对象应该在onCreate(...)完成后超出范围,并且预期的行为onLocationChanged是从未调用或调用几次,直到对象被垃圾回收.但是,返回的对象getSystemService似乎是单例,它存在于范围之外MainActivity(因此它是一个系统服务:)

在进行堆转储并使用Eclipse Memory Analyzer完成后,似乎ContextImpl保留了对LocationManager实例的引用.在内存转储中有两个对LocationManager对象的引用,而在代码中显然只有一个,这意味着在其他地方创建了另一个引用.

我的问题是:

在调用以下实现时,是否有人完整地描述了正在发生的事情:

public abstract Object getSystemService(String name);
Run Code Online (Sandbox Code Playgroud)

是一个懒惰创建的单例返回的对象,创建/保留引用的确切位置是什么?

package com.neusoft.bump.client.storage;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

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

        Log.v("TAG", "STARTED");
        LocationManager mLocationManager = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);

        LocationListener locationListener = new LocationListener() {

            public void onLocationChanged(Location location) {
                Log.v("TAG", "onLocationChanged");
                Log.v("TAG", "Latitude: " + location.getLatitude() …
Run Code Online (Sandbox Code Playgroud)

android locationmanager

25
推荐指数
2
解决办法
3万
查看次数

标签 统计

android ×1

locationmanager ×1