how to quite a Looper of a worker thread

224 views Asked by At

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();
    }

}


}
0

There are 0 answers