gpt4 book ai didi

android - 在单独的线程上使用 HandlerThread 和 Handler 会卡住 UI 线程

转载 作者:行者123 更新时间:2023-11-30 02:50:59 24 4
gpt4 key购买 nike

在我的项目中,我想在另一个线程中实现一个计时器,用于计算在我的应用程序中执行某个方法所花费的时间,并在花费太多时间时做一些事情。执行 MyManager.startCommand() 方法时,应用程序卡住,我不知道为什么,因为我认为我没有在 UI 线程上做任何事情。我的代码有什么问题吗?

我最初问过这个问题并且没有遇到应用程序卡住,所以我不认为这是因为我正在休眠线程:Runnable posted in another runnable not executed .

public class MyManager{
private MyManager sInstance;
private HandlerThread mHandlerThread;
private Handler mHandler;
private Runnable mTimeoutTimer;

public static MyManager getInstance(){
if(sInstance == null){
sInstance = new MyManager();
}
return sInstance;
}

private MyManager(){
mHandlerThread = new HandlerThread("mHandlerThread");
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper());
mTimeoutTimer = new Runnable() {
@Override
public void run() {
Log.e(“RUNNABLE RUNNING!”);
}
};

public class MyCommand {
private Runnable myRun;

public MyCommand(){
myRun = new Runnable() {
@Override
public void run() {
MyManager.getInstance().startTimeoutTimer();
MyCommand.this.run();
}
};
}

public void execute() {
myRun.run();
}

abstract public void run();
}


private void startTimeoutTimer(){
mHandler.post();
}


public void startCommand(){
new MyCommand().execute();
}
}

以及我如何使用 MyCommand 对象:

MyCommand command =
new MyCommand() {
@Override
public void run() {
//make api call that happens in another thread
}
};

所以我基本上是在尝试为该 API 调用创建超时计时器。

最佳答案

试试这个:

只需将您的第一个可运行对象包装在线程中即可。

public class MyManager{
private MyManager sInstance;
private HandlerThread mHandlerThread;
private Handler mHandler;
private Runnable mTimeoutTimer;

public static MyManager getInstance(){
if(sInstance == null){
sInstance = new MyManager();
}
return sInstance;
}

private MyManager(){
mHandlerThread = new HandlerThread();
mHandler = new Handler(mHandlerThread.getLooper());
mTimeoutTimer = new Runnable() {
@Override
public void run() {
Log.e(“RUNNABLE RUNNING!”);
}
};

public class MyCommand {
private Thread th;
private Runnable myRun;

public MyCommand(){
myRun = new Runnable() {
@Override
public void run() {
MyManager.getInstance().startTimeoutTimer();

try {
Thread.sleep(COMMAND_TIMEOUT_MILLIS * 3);
} catch (InterruptedException e) {}

MyCommand.this.execute();
}
};
th = new Thread(myRun);
}

public void execute() {
th.start();
mHandler.postDelayed(mTimeoutTimer);
}
}


private void startTimeoutTimer(){
mHandlerThread.start();
mHandler.postDelayed(mTimeoutTimer);

}


public void startCommand(){
new MyCommand().execute();
}

你还忘了启动mHandlerThread

    private void startTimeoutTimer(){
mHandlerThread.start();
mHandler.postDelayed(mTimeoutTimer);

}

关于android - 在单独的线程上使用 HandlerThread 和 Handler 会卡住 UI 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24173049/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com