我有这个设置
MainActivity类创建BTHandler,它是一个实用程序类。它传递活动上下文和应用程序上下文。
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);
}
};
}
这是Utiliy课程。它使用上下文进行某些计算,并在需要时创建ConnectThread,以启动与BT设备的连接。它传递活动上下文,因此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();
}
}
最后这里出现了错误。这是ConnectThread。我想从此处向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可以看到处理程序?
答案 0 :(得分:0)
您可以将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
答案 1 :(得分:0)
您还可以定义公共和静态MainActvity变量,并在其他类中使用它:
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);
}
};
}
和你的其他课程:
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();
}
}