Error while working with getLooper() method in android

79 Views Asked by At

I am learning threading and concurrency in Android. I have created a basic program where the main thread sends an interrupt to the worker thread to stop the worker thread's processing. The main thread sends the interrupt after 5 seconds. I have 2 threads: a main thread and a worker thread.

Code:

package com.example.testthread;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private Handler mHandler;


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

        // Create a new thread and start it
        NewThread newThread = new NewThread();
        newThread.start();

        // Get the Looper of the new thread and create a Handler associated with it
        Looper looper = newThread.getLooper();

        mHandler = new Handler(looper);

        // Post a Runnable to the new thread's Handler after a delay of 5 seconds
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                newThread.interrupt();
            }
        }, 5000);
    }

    private static class NewThread extends Thread {

        private boolean isRunning = true;

        @Override
        public void run() {
            Looper.prepare();
            while (isRunning) {
                Log.d("NewThread", "Thread is running");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Log.d("NewThread", "Thread was interrupted");
                    isRunning = false;
                }
            }
            Looper.loop();
        }

    }
}

Here, the getLooper() method is giving me error

enter image description here

Unable to solve the issue. Help will be appreciated!

1

There are 1 best solutions below

0
snachmsm On

your NewThread doesn't have getLooper() method, also Thread itself. if you really need outer access to that looper you can look at source of HandlerThread and copy its realisation of stored-locally-Looper-mLooper for getting getLooper() method also in your NewThread

    Looper.prepare();
    synchronized (this) {
        mLooper = Looper.myLooper(); // obtain ref between prepare() and loop()
        notifyAll();
    }
    Looper.loop();

or just use HandlerThread strictly...