我需要使用AsynTask或AsynTaskLoader,一切都很顺利但是当我尝试在这个子类中使用Context时,会出现泄漏内存问题,请问我该如何解决这个问题?
this is my code:
class GeoTask(var context: Context, var latitude:Double, var longitude:Double ):AsyncTask<Util, Util, Unit>() {
override fun doInBackground(vararg p0: Util?) {
val geocoder = Geocoder(context, Locale.getDefault())
val addresses = geocoder.getFromLocation(latitude, longitude, 1)
if (addresses != null && addresses.size > 0 && Geocoder.isPresent()) {
LocationUtil.country_name = addresses[0].countryName
LocationUtil.city_name = addresses[0].locality
}
}
}
答案 0 :(得分:0)
您可以尝试使用WeakReference
。
例如
internal class GeoTask(var context: WeakReference<Context> .... {
override fun doInBackground(vararg p0: String?) {
val geocoder = Geocoder(context.get(), Locale.getDefault())
....
}
这就是我的尝试:
class MainActivity : AppCompatActivity
{
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Test(WeakReference<Context>(this@MainActivity)).call()
}
class Test(val weakReference: WeakReference<Context>)
{
fun call()
{
Toast.makeText(weakReference.get(), "WeakReference Demo", Toast.LENGTH_SHORT).show()
}
}
}