0

I wrote the below code to better understand the Handler and the Looper. I would liek to know how can I quit the Looper on occurence of a specific condition for example, when a counter reaches a specific limit.

In the below code, I want to call .quit() on the looper of the Thread T when "what" is equal to 10. According to the code i wrote below, even when the contents of "what" exceeds 10, the "handleMessage" method is getting called...i expected that when .quit() is called, the "handleMessage" will no longer be called.

please let me know how can I properly quit a Looper.

app.gradle

public class ActMain extends AppCompatActivity {

private static final String TAG = ActMain.class.getSimpleName();
private Handler mHandler = null;
private Button mBtnValues = null;
private int i = -1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_act_main);

    this.mBtnValues = findViewById(R.id.btnValues);
    this.mBtnValues.setOnClickListener(x-> {
        Message msg = new Message();
        Bundle bundle = new Bundle();
        bundle.putString("what", "" + i++);
        Log.d(TAG, "i: " + i);
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    });
    new T().start();
}

private class T extends Thread {
    private String str = "";

    public T() {}

    @Override
    public void run() {
        super.run();
        Log.d(TAG, "run method started");
        Looper.prepare();

        Log.d(TAG, "beginning of the looped section");
        final String[] cnt = {""};
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                String what= msg.getData().getString("what");
                str += what;
                Log.d(TAG, "new str: " + str);
            }
        };
        Log.d(TAG, "end of the looped section");
        if (i == 10) {
            Looper.myLooper().quit();
        }
        Looper.loop();
    }

}


}
Amrmsmb
  • 1
  • 27
  • 104
  • 226
  • You can access the Looper associated with your thread through `Looper.myLooper().quit();` instead of `getMainLooper().quit();` – Mark Nov 24 '18 at 23:58
  • @MarkKeen i tried to use Looper.myLooper.quite() as you suggested...but still i can click the button more than 10 times and still the handler object inside the run method can keep prints the value no matter the value of i is....i modified the question..would you please have a look and help me quite the looper when the value of i == 10?? – Amrmsmb Nov 25 '18 at 11:53
  • you should make the `int i` volatile, meaning that it's value is never cached and always referenced to the same variable. – Mark Nov 25 '18 at 14:05

0 Answers0