You can not do Thread.sleep(...) in the UI-stream, because if you block the UI-stream, then after a few seconds, get ANR ( Application not responding ) with a proposal to force the application to stop. And generally it is impossible to load a UI stream.
In your task, you need to create a new stream in which your method will be executed and use synchronization of threads (for example) on any object.
Here is the most primitive code that performs the task:
public class MainActivity extends AppCompatActivity { private Button mFirstButton; private Button mSecondButton; private static final Object sMonitor = new Object(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mFirstButton = (Button) findViewById(R.id.first_button); mSecondButton = (Button) findViewById(R.id.second_button); mFirstButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { Log.d("TAG", "Start"); synchronized (sMonitor) { try { sMonitor.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("TAG", "End"); } }).start(); } }); mSecondButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { synchronized (sMonitor) { sMonitor.notify(); } } }); } }
When the mFirstButton button is mFirstButton , a new stream is launched, a corresponding message is output to the log, then the stream enters the synchronized block, the wait() method is executed and the stream falls asleep.
Further, when mSecondButton , the UI stream enters the synchronized block (it can enter because the thread started by the mFirstButton button after calling wait() no longer owns the monitor) and causes notify() , which entails resuming the flow, created by the mFirstButton button.
UPD :
In order to execute code in the main thread, you can use, for example, the runOnUiThread(...) method:
runOnUiThread(new Runnable() { @Override public void run() { // actions on UI-thread } });
while (!isClicked) { Thread.sleep(1000); }while (!isClicked) { Thread.sleep(1000); }setting theisClickedvalue totruein the keystroke handling method? - RegentaskQuestionXXmethods? - Regent