Reputation: 3807
There is apparently a memory, most likely with this method. The leak was so bad that it crashed my entire phone's os, forcing a restart. What is the exact cause of the memory leak? What are other alternatives to fix this?
public void mainControl(){
Timer mainTimer = new Timer();
mainTimer.scheduleAtFixedRate(new TimerTask(){
public void run(){
runOnUiThread(new Runnable(){
public void run(){
getDateTime();
getBattery();
getFreeSpace();
getLocation();
getBearing();
getMoon();
getPressure();
}
});
}
}, 0, 1000);
}
Upvotes: 0
Views: 1329
Reputation: 51
I had problems with timer task a lot of times in the same code. I read that a solution is create your own TimerTask instead of a anonymous class (because it depends of Activity context)
private class MyTimerTask() : TimerTask(){
override fun run() {
//
}
}
Finally, I changed TimerTask to Handler. Sorry, Kotlin:
import android.os.Handler
private var mHandler: Handler? = Handler()
private var myRunnable: Runnable = object : Runnable {
override fun run() {
update()
mHandler?.postDelayed(this, 1000)
}
}
fun update(){
//something
if ([Condition to finish]){
mHandler?.removeCallbacks(myRunnable)
mHandler = null
}
}
fun pause(){
mHandler?.removeCallbacks(myRunnable)
}
fun startResume() {
myRunnable.run()
}
Upvotes: 0
Reputation: 559
I suggest you use AsyncTask when working with threads. And the reason for memory leaks are probably inside your methods that you are calling.
private class BackgroundAsyncTask extends AsyncTask<Object, Void, String> {
@Override
protected String doInBackground(Object... args) {
//because our args are type Object that basically means we dont have to pass any value or variable to this async task
getDateTime();
getBattery();
getFreeSpace();
getLocation();
getBearing();
getMoon();
getPressure();
return "";//return nothing
}
@Override
protected void onPostExecute(String result) {
//this is where if you are going to do something with the returned value you would do the stuff that interacts with the main UI. Leave this blank unless you have those methods changing stuff on the main UI.
}
}
new BackgroundAsyncTask().execute();//this is how to call this async task
Thing to note: If your methods such as getDateTime(); are interacting with the UI then you have to change this code slightly. Tell me and I can help there too.
Upvotes: 1