gpt4 book ai didi

java - 调试卡住的 Android 应用程序

转载 作者:行者123 更新时间:2023-12-01 12:48:36 26 4
gpt4 key购买 nike

我有一个带有三个线程的 Android 应用程序,即主线程和两个工作线程。线程需要定期相互通信。

我最初以一种可怕的方式去做这件事,这里的每个人都会对我大喊大叫。我在每个线程中保存了线程的实例,并在线程需要该功能时从其他线程调用该类的方法。它有效,但我知道这是不对的。

由于这是错误的,我返回并将线程的每个实例更改为线程处理程序的实例,并将每个线程函数调用替换为 handler.sendMessage 调用。

现在程序无法运行。它只是卡住了,我不知道发生了什么。使用调试视角时,我单步执行主线程,但我得到的只是函数

boolean hasMessages(Handler h, int what, Object object)
{
...
}

来自消息队列。其他线程在它们的 run() 函数中循环,它没有做任何令人兴奋的事情。我的日志都没有打印。我对正在发生的事情感到茫然,我不知道下一步应该采取什么步骤来继续调试它。我所做的只是添加处理程序和发送消息。你们能建议我应该采取哪些后续步骤来进行调试吗?

编辑:这是一些代码,我运气不好

主要 Activity :

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
connectionStatusTextView = (TextView) findViewById(R.id.connectionStatus);
imageView = (ImageView) findViewById(R.id.imageView);
commandView = (TextView)findViewById(R.id.commandView);
focusView = (TextView)findViewById(R.id.focusView);
mApplication = ((myApplication) this.getApplication());

ConnectedThread connectedThread = new ConnectedThread(mHandler, mApplication);
VoiceRecognitionThread voiceThread = new VoiceRecognitionThread(mApplication, this);

connectedThread.setHandlers(mHandler, voiceThread.getHandler());
voiceThread.setHandlers(mHandler, connectedThread.getHandler());

connectedThread.start();
voiceThread.start();
}

ConnectedThread 和 VoiceRecognitionThread 都扩展了 HandlerThread。它们都创建一个类级别的 Handler 来处理发送到这些线程的消息。 getHandler 返回对这些处理程序的引用。

最佳答案

只需使用 HandlerThread并通过其处理程序对象向其提供消息:

HandlerThread thread1 = new HandlerThread("Thread Name");
thread1.start();
handler1 = new MyHandler(thread1.getLooper());

// pass message for thread 1
handler1.sendmessage()

// and same for threads 2 and 3

请注意,如果您计划线程长时间运行,则更好解决方案是使用 IntentService .

IntentService 是服务,因此,到目前为止不太容易受到Android 回收然后资源变低。

关于java - 调试卡住的 Android 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24438478/

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