Android 如何删除对象

Android how to delete an object

所以我正在制作一个箭头指向某个地理位置点的应用程序。在我的程序中,每次 phone 移动时都会调用 GPSTracker class 的新实例。问题出现在 运行 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)。如前所述,应用程序冻结是因为对象似乎没有立即被丢弃。

每当你想从内存中显式删除一个对象时,你想做的是:

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

试试这个。这应该有效。

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

GPSTracker gpsTracker;

public GPSTracker getGPSTrackerInstance() {

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

    return gpsTracker;
}

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