I use code like below for periodic execution
but i am suspecting a memory leak
Maybe my code is wrong?
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
if(isRunning)
{
...code
}
handler.postDelayed(this, 5000);
}
};
handler.postDelayed(runnable, 5000);
This is the code that uses another handler
private Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
mHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(#NonNull Message msg) {
return true;
}
});
}
Related
TextView output;
int i;
Random random=new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
output=findViewById(R.id.textView);
new Thread(new mythread()).start();
}
class mythread implements Runnable{
#Override
public void run() {
try {
while(true) {
i = random.nextInt(100);
output.setText(i + "");
Thread.sleep(500);
}
}catch (Exception e){}
}
}
}
it just showing one number in text view
but requirement is ,it should generate random number and keep updating textview after 500ms
Thank You!
The main problem, in your code, is that you can update UI only in the main thread and you are using a custom thread.
The second problem is that you are using Thread.sleep that is a very bad practise.
I suggest you to use Handler
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
Log.d("Handler", "Running Handler");
handler.postDelayed(this, 500);
}
}
handler.postDelayed(runnable, 0);
and here the kotlin version
var handler = Handler()
var runnable = object : Runnable {
override fun run() {
Log.d("Handler", "Running Handler");
handler.postDelayed(this, 500)
}
}
handler.postDelayed(runnable, 500)
Try this, I think it will solved your problem.
public class MainActivity extends AppCompatActivity {
private Random random;
private Handler handler;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.tv_number);
displayRandomNumber();
}
/**
* Display random number in text view
*/
private void displayRandomNumber()
{
random = new Random();
handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
int value = random.nextInt();
textView.setText(String.valueOf(value));
handler.postDelayed(this,2000);
}
}, 2000);
}
}
this is a simple code to understand the runnable .I tried but not working . can you guys help me pls this is my code
public class Autostart extends activity implements Runnable {
#override
public void run (){
System.out.println ("message");
}
}
}
this not printing any statements
If you are using an Activity, you need to write your code inside Activity lifecycle methods. onCreate() is called when the Activity is created. So starting your Runnable here would be the correct way to do it.
#Override
public void onCreate(Bundle savedInstanceState) {
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
System.out.println ("message");
}
};
handler.postDelayed(r, 1000);
}
You have to create a Thread object and call start() using that object.
Thread t = new Thread(this);
t.start();
Or Just use Handler
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do Something here
}
}, 5000);
You can use below code to print a value after regular interval of time
public void callAsynchronousTask() {
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
Log.e("on print timee", your value);
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 1000); // will execute after 1 sec
}
Hope this will help you
I found a similar solution to Swayam (android implements runnable not working?), however another handler.postDelayed reference within run() was required;
public void onCreate(
...
final Handler handler = new Handler();
final Runnable r = new Runnable()
{
public void run()
{
Log.i(TAG, "message");
handler.postDelayed(this, 1000);
...
}
};
handler.postDelayed(r, 1000);
Try following code
Handler mainThreadhandler = new Handler(getMainLooper());
mainThreadhandler.post(new Runnable(){
public void run(){
// UI work
}
});
public class Autostart extends activity implements Runnable {
Thread = thread;
#override
public void onCreate() {
thread = new Thread(this);
thread.start();
}
#override
public void run (){
System.out.println ("message");
}
}
I have a looper and handler:
private Handler handler;
public class LooperThread extends Thread
{
#Override
public void run()
{
Looper.prepare();
handler = new Handler()
{
#Override
public void handleMessage(Message message)
{
updateUI(message.obj);
}
};
Looper.loop();
}
}
In my MainActivity I then call:
new LooperThread().start();
new Thread(new WorkerTask()).start();
Where WorkerTask implements Runnable.
Can't create handler inside thread that has not called Looper.prepare().
Inside my workerTask it is throwing the error on the second line:
locationManager = (LocationManager) activity.getSystemService(activity.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
If this is in Activity or fragment you can simply use runOnUiThread to update ui.
You need to use this:
activity.runOnUiThread(new Runnable() {
public void run() {
updateUI(message.obj);
}
});
Or to use it with your existing code:
private Handler handler;
public class LooperThread extends Thread
{
#Override
public void run()
{
Looper.prepare();
handler = new Handler()
{
#Override
public void handleMessage(Message message)
{
activity.runOnUiThread(new Runnable() {
public void run() {
updateUI(message.obj);
}
});
}
};
Looper.loop();
}
}
I tried to create a small timer for my programm but this code below is not working and i cant find the issue
private int mInterval = 5000;
private Handler mHandler;
// at the bottom of my onCreate() methode:
mHandler = new Handler();
startRepeatingTask();
}
// on create ends here
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
myview.loadUrl(readFromFile());
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
I really would appreciate your help.
Something like this should work :)
//set variables
private int mInterval = 5000;
private Handler handler = new Handler();
//start runnable
runme.run();
private Runnable runme = new Runnable()
{
public void run()
{
//repeat after 5000 milliseconds
handler.postDelayed(this, mInterval );
}
};
//stop runnable
handler.removeCallbacks(runme);
try this..
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
// do something here...
handler.postDelayed(this, 5000); // for interval...
}
};
handler.postDelayed(runnable, 2000);
Try this
private int mInterval = 5000;
private Handler mHandler;
// at the bottom of my onCreate() methode:
mHandler = new Handler();
mHandler.postDelayed(mStatusChecker,mInterval);
}
// on create ends here
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
myview.loadUrl(readFromFile());
//if you want to repeat the thread infinitely,then add below code also. Else remove it
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
Use Handler.post() or Handler.postDelayed() to start a Handler.
private int mInterval = 5000;
private Handler mHandler;
// at the bottom of my onCreate() methode:
mHandler = new Handler();
mHandler.post(mStatusChecker);
//mHandler.postDelayed(mStatusChecker, mInterval);//or use this method
//startRepeatingTask();
// on create ends here
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
myview.loadUrl(readFromFile());
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
//void startRepeatingTask() {
// mStatusChecker.run();
//}
You may need to add android.permission.WRITE_EXTERNAL_STORAGE for read file in storage, and android.permission.INTERNET for load url.
I have the below singleton handler class
public class MyHandler
{
private static Handler handler;
private static boolean isRunning;
public static Handler getHandler(Runnable myRunnable)
{
if (handler == null)
{
initHandler(myRunnable);
}
return handler;
}
private static void initHandler(Runnable myRunnable)
{
handler = new Handler();
isRunning = true;
handler.postDelayed(myRunnable, 5000);
}
public static void reRunHandler(Runnable myRunnable)
{
isRunning = true;
handler.postDelayed(myRunnable, 45000);
}
public static void stopMyHandler()
{
isRunning = false;
handler.removeCallbacksAndMessages(null);
}
}
However, how can I update my UI from here ? As the runnables are inside my activity. Apparently I cannot use getHandleMessage to communicate with it.
If you need more code, how am I using this, I can share.
It's very simple:
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
//do whatever you want on the UI thread
}
});
Handle has functions for this purposes:
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
// here you can get data from Message and update your UI. runs in UI thread
}
};
If you will send message with data to your Handler use next code:
Message m = new Message();
Bundle b = new Bundle();
b.putInt("myNumber", 5); // for example
m.setData(b);
myHandler.sendMessage(m);