在 android 中使用 getLooper() 方法时出错

问题描述 投票:0回答:1

我正在学习 Android 中的线程和并发。我创建了一个基本程序,其中主线程向工作线程发送中断以停止工作线程的处理。主线程在 5 秒后发送中断。我有 2 个线程:一个主线程和一个工作线程。

代码:

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

    }
}

在这里,getLooper() 方法给我错误

无法解决问题。帮助将不胜感激!

android multithreading concurrency java-threads android-looper
1个回答
0
投票

你的

NewThread
没有
getLooper()
方法,也没有
Thread
本身。如果你真的需要外部访问那个活套,你可以查看
HandlerThread
的来源并复制它的实现 stored-locally-
Looper
-
mLooper
以获得
getLooper()
方法也在你的
NewThread

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

或者严格使用

HandlerThread
...

© www.soinside.com 2019 - 2024. All rights reserved.