Created
May 2, 2018 07:35
-
-
Save burhanaras/65f5debb3f38255a51fa552b27152746 to your computer and use it in GitHub Desktop.
This AsyncTask class should be static or leaks might occur
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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