Skip to content

Instantly share code, notes, and snippets.

@burhanaras
Created May 2, 2018 07:44
Show Gist options
  • Save burhanaras/f158d4e386d05bcb92afade6ef5b3f16 to your computer and use it in GitHub Desktop.
Save burhanaras/f158d4e386d05bcb92afade6ef5b3f16 to your computer and use it in GitHub Desktop.
This AsyncTask class should be static or leaks might occur
import android.os.AsyncTask
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.burhan.studentattendance.R
import java.lang.ref.WeakReference
class MainActivity : AppCompatActivity() {
private var mJustAVariable = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
MyAsyncTask(this).execute()
}
private class MyAsyncTask internal constructor(context: MainActivity) : AsyncTask<Void, Void, String>() {
private val activityReference: WeakReference<MainActivity> = WeakReference(context)
override fun doInBackground(vararg params: Void): String {
// do some long running task...
return "task finished"
}
override fun onPostExecute(result: String) {
// get a reference to the activity if it is still there
val activity = activityReference.get()
if (activity == null || activity.isFinishing) return
// access Activity member variables or modify the activity's UI
activity.mJustAVariable = 123
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment