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
Unable to solve the issue. Help will be appreciated!