从可运行界面访问 activity 上下文

Access activity context from runnable interface

我有这个设置

MainActivity Class 创建 BTHandler,这是一个实用程序 class。它传递 activity 上下文和应用程序上下文。

public class MainActivity extends Activity implements View.OnClickListener{

    protected void onCreate(Bundle savedInstanceState) {
     ...
    currentBT = new BTHandle(this, MainActivity.this);
    }

    public Handler handler = new Handler() {
    @Override
    public void handleMessage(android.os.Message msg) {
        ...
        super.handleMessage(msg);
    }
};
} 

这是实用程序 class。它使用上下文进行一些计算,并在需要时创建 ConnectThread,以启动与 BT 设备的连接。它传递 activity 上下文,因此 ConnectThread 可以通过处理程序发送消息。

class BTHandle { 
    private final Context mainActivityContext;
    private final Activity mainActivity;
    ...
    public BTHandle(final Context context, final Activity activity){
        mainActivityContext = context;
        mainActivity = activity;
    }
    f(){
        ConnectThread connectAsClient = new ConnectThread(mainActivityContext, BTDevice, mBluetoothAdapter, BTUuid);
        new Thread(connectAsClient).start();
    }

}

最后错误来了。这是连接线程。我想从这里向 MainActivity 发送消息。但是编译器说它无法解析处理程序。所以我猜上下文没有通过它。

public class ConnectThread implements Runnable {
     private final Context mainActivity;
     public ConnectThread(Context context, BluetoothDevice device, BluetoothAdapter adapter, UUID BT_UUID) {
     ...
     mainActivity = context;
     }

     @Override
     public void run() {
         ...
       Message completeMessage = mainActivity.handler.obtainMessage(555, "CONNECTED");
       completeMessage.sendToTarget();
     }
}

如何以正确的方式传递上下文以便 ConnectThread 可以看到处理程序?

您可以将 MainActivity 对象一直传递到 ConnectRunnable 即:

private final MainActivity mainActivity;
public ConnectThread(MainActivity context, BluetoothDevice device,
BluetoothAdapter adapter, UUID BT_UUID) {
 ...
 mainActivity = context;
 }

或将您的呼叫更改为:

 Message completeMessage = 
((MainActivity)(Activity)mainActivity)).handler.obtainMessage(555, "CONNECTED");

此外,您的处理程序必然会泄漏内存。 看看这个修复:How to Leak a Context: Handlers & Inner Classes

您还可以定义一个 public 和静态 MainActvity 变量并在您的其他 class 中使用它:

public class MainActivity extends Activity implements View.OnClickListener{
public static MainActivity mainActivity;
protected void onCreate(Bundle savedInstanceState) {
 ...
mainActivity = this;
currentBT = new BTHandle(this, MainActivity.this);
}

public Handler handler = new Handler() {
@Override
public void handleMessage(android.os.Message msg) {
    ...
    super.handleMessage(msg);
}
};
} 

在你的另一个 class 中:

public class ConnectThread implements Runnable {
private MainActivity mainActivity;
 public ConnectThread(Context context, BluetoothDevice device, BluetoothAdapter adapter, UUID BT_UUID) {
 ...
 mainActivity = MainActivity.mainActivity;
 }

 @Override
 public void run() {
     ...
   Message completeMessage = mainActivity.handler.obtainMessage(555, "CONNECTED");
   completeMessage.sendToTarget();
 }
}