gpt4 book ai didi

java - 如何在Activity和其他Activity创建的线程之间进行通信

转载 作者:行者123 更新时间:2023-12-02 02:09:27 25 4
gpt4 key购买 nike

当您有 2 个 Activity ( A 和 B )并且 A 是 MainActivity 时,现在您启动您的应用程序,A 启动 B。B 是一个带有与用户交互的对话框的 Activity ,创建蓝牙连接和 2 个线程,1 个接收线程和 1 个发送线程。现在,将信息从 A 发送到 B 的线程以及反之亦然的最佳方式是什么? Look here.

首先我使用了静态WeakReference,但我听说这会导致很多问题,所以我想寻求一个更通用的解决方案。

请记住,当从另一个 Activity 启动一个 Activity 时,只能传递可序列化的 Objs 和简单数据。因此不可能以这种方式使用处理程序。

这是我使用的静态 WeakReference:

public class T1 extends Thread{
private static WeakReference<T1> weak_T1;


public void T1 (){
weak_T1 = new WeakReference<T1> (This);
}

public static WeakReference getWeakReverence() {
return weak_T1;
}

}

以下是在堆栈中查找正在运行的线程的方法:

for (Thread thread : Thread.getAllStackTraces().keySet()) { 
if (thread.getName().equalsIgnoreCase("T1")){
T1A =thread;
}else if (thread.getName().equalsIgnoreCase("T2")){
T2A =thread;
}
}

还有可能的解决方案:

public class example extends Thread {
private static example instance;

private example() {
}

public static example getIsntance(){
if(instance == null){
instance = new example();
}

return instance;
}
}

最佳答案

WeakReference 可能不是您想要的。也就是说,假设您的 Thread 对象要么不会终止,要么在 Activity B 停止后以某种方式维护一些对 Activity A 有用的信息。如果您使用WeakReference,一旦 Activity B 结束并且线程终止,它可能会变为“null”。只需使用常规的旧强引用即可。它将确保 T1 及其包含的信息继续存在,直到您用完为止。

public class ActivityB extends Activity
{
private T1 t1;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
t1 = startMyThread();
}

@Override
public void onBackPressed()
{
ActivityA.tempT1 = t1;

//This technique presumes that Activity A is guaranteed to resume after a
//back button press, based on the arrangement of your backstack, etc. If
//Activity A is started via some other means (e.g., an explicit startActivity(),
//finish(), etc.), then this reference will have to be set prior to
//that call, as well, in order to establish the appropriate "happens before" relationship.
//If you fail to ensure that Activity A resumes after this point, you will
//risk a memory leak.

super.onBackPressed();
}
}

public class ActivityA extends Activity
{
public static T1 tempT1 = null;
private T1 t1;

@Override
public void onResume()
{
super.onResume();
if(tempT1 == null)
{
//Apparently, Activity B hasn't executed yet. Provide the user with a button to start it.
}
else
{
t1 = tempT1;
tempT1 = null; //To avoid a memory leak

//We just retrieved the reference that Activity B left for us.
//Now, change UI states so that the user can see information about t1.
}
}
}

关于java - 如何在Activity和其他Activity创建的线程之间进行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57337006/

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