【发布时间】:2026-01-08 15:50:01
【问题描述】:
我正在后台运行一项服务,该服务也绑定到一个活动,以向视图提供一些数据结果。 所以我的服务在后台运行,我在我的活动开始时绑定服务,并在它关闭时解除绑定,而不管我的后台服务是否不断运行。 当我的活动第一次开始时,首先触发此服务。
现在我在服务中创建了两个线程。一个用于后台工作。其他线程“displayThread”用于获取数据并将数据推送到活动。
现在我的显示线程是这样的:
Thread displayThread = new Thread(new Runnable() {
@Override
public void run() {
try {
executeDisplayQueue();
} catch (InterruptedException e){
displayThread.interrupt();
}
}
});
因此,当我的活动开始时,我的服务开始,并且我正在启动两个线程:
@Override
public void onCreate() {
super.onCreate();
Log.d(LOG_TAG, "Creating Service......");
thread.start();
displayThread.start();
Log.d(LOG_TAG, "Service is created.");
}
现在我想要的是,当我在 Activity 关闭时解除绑定我的服务时,我的“displayThread”会停止或暂停,并在再次启动调用 rebind() 函数的 Activity 时重新启动或恢复。
@Override
public boolean onUnbind(Intent intent) {
super.onUnbind(intent);
// Stop/Pause/Wait my displayThread here
return true;
}
@Override
public void onRebind(Intent intent) {
super.onRebind(intent);
// Restart/Resume my displayThread here
Log.d(LOG_TAG, "trying to check display thread");
}
请帮助我,因为我尝试了很多东西。 现在 displayThread.wait() 暂停了我的应用程序屏幕,所以它变黑了,好像一切都停止了,这当然不是正确的方法。
请给我一个关于如何进一步进行的解决方案。
编辑
这是executeDisplayQueue()函数:
@Override
protected void executeDisplayQueue() throws InterruptedException {
Log.d(LOG_TAG, "Starting execution of queue...");
while (!Thread.currentThread().isInterrupted()) {
SomeJob job = null;
try {
job = jobShowQueue.take();
Log.d(LOG_TAG, "Taking Job no. " + job.getId() + " from the queue...");
if (job.getJobState().equals(JobState.NEW)) {
Log.d(LOG_TAG, "Job state is NEW.");
job.setJobState(JobState.RUNNING);
job.getCmd().run(bluetoothSocket.getInputStream(), bluetoothSocket.getOutputStream());
} else {
Log.e(LOG_TAG, "Job state is not NEW and therefore it should not be in Queue");
}
} catch (InterruptedException ie){
Thread.currentThread().interrupt();
} catch (UnsupportedCommandException u) {
if (job != null)
job.setJobState(JobState.NOT_SUPPORTED);
} catch (IOException ioe){
job.setJobState(JobState.BROKEN_PIPE);
Log.e(LOG_TAG, "Broken Pipe Error. Close the connection and restart again: "+ioe.getMessage());
} catch (Exception e){
job.setJobState(JobState.EXECUTION_ERROR);
Log.e(LOG_TAG, "Failed to run Command. Error: "+e.getMessage());
}
if (job != null){
Log.d(LOG_TAG, "Job is Finished.");
final SomeJob finalJob = job;
((Activity) applicationContext).runOnUiThread(new Runnable() {
@Override
public void run() {
((Activity) applicationContext).stateUpdate(finalJob);
}
});
}
}
}
所以基本上我是从队列中一个一个地取出作业并将其填充到活动中。所以当我的活动关闭时,我希望这个线程(displayThread)停止,因为它不再需要填充任何东西。当它再次打开时,我的 displayThread 应该会自行重启。
【问题讨论】:
标签: java android multithreading service