【问题标题】:Android how to delete an objectAndroid如何删除一个对象
【发布时间】:2015-04-23 00:05:18
【问题描述】:

所以我制作了一个应用程序,其中箭头指向某个地理位置点。在我的程序中,每次手机移动时都会调用 GPSTracker 类的新实例。运行应用程序 10 秒后冻结时会出现问题。我需要在创建新的 gpsTracker 之前以某种方式丢弃 gpsTracker。 `

@Override
    public void onSensorChanged(SensorEvent event) {
    GPSTracker gpsTracker =  gpsTracker = new GPSTracker(this);
    float azimuth = event.values[0];
    Float TrueNorth, theta, beta, aplha;
    Location curloc = new Location("Current Location");
    Location destloc = new Location("Destination Location");
    Float f = 0.000621371F;
    curloc.setLatitude(gpsTracker.getLatitude());
    curloc.setLongitude(gpsTracker.getLongitude());
    destloc.setLatitude(47.66432);
    destloc.setLongitude(-122.08458);

     Float h = getMiles(curloc, destloc);
     Double g = Double.valueOf(h);
    tvHeading.setText(g.toString() + " Miles");
    GeomagneticField geoField = new GeomagneticField(Double
        .valueOf(curloc.getLatitude()).floatValue(), Double
        .valueOf(curloc.getLongitude()).floatValue(), Double
        .valueOf(curloc.getAltitude()).floatValue(),
            System.currentTimeMillis());

    azimuth -= geoField.getDeclination();
    float bearTo = curloc.bearingTo(destloc);

    if(bearTo <0){
        bearTo = bearTo + 360;
    }

    float direction = bearTo - azimuth;

    if(direction <0){
        direction = direction + 360;
    }

    RotateAnimation ra = new RotateAnimation(
            currentDegree, -direction, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
            0.5f
    );
    ra.setDuration(210);
    ra.setFillAfter(true);
    Image.startAnimation(ra);
    currentDegree = direction;

    if(curloc == destloc){
        tvHeading.setText("Arrived At Destination!");
    }

}

` 从代码中可以看出,GPSTracker gpsTracker = new GPSTracker(this) 已创建。如前所述,应用程序冻结是因为对象似乎没有被立即丢弃。

【问题讨论】:

  • 所以只创建一个实例作为类成员。

标签: java android gps garbage-collection finalize


【解决方案1】:

您可以在这里使用单例概念,如果该对象存在则不要创建,否则创建它。

GPSTracker gpsTracker;

public GPSTracker getGPSTrackerInstance() {

    if(gpsTracker == null) 
        gpsTracker = new GPSTracker();

    return gpsTracker;
}

此方法将创建GPSTracker 类对象,如果它的对象不存在,否则不存在。

【讨论】:

  • @Rifat 很高兴为您提供帮助 :)
【解决方案2】:

当你想明确地从内存中删除一个对象时,你想做:

gpsTracker.finalize();
gpsTracker = null;
System.gc();

试试这个。这应该可以。

【讨论】:

  • 我尝试使用您的方法,但是将对象设置为 finalize 给我一个错误
猜你喜欢
  • 1970-01-01
  • 2012-01-08
  • 2011-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-23
  • 2015-04-04
相关资源
最近更新 更多