尝试使用线程时出现此错误。
Can't create handler inside thread that has not called Looper.prepare()
Thread anOpenConnectionThread = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
openConnection();
}
catch (Exception err)
{
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(LaunchApp.this, "Opening connection with " + ip + " failed!", Toast.LENGTH_SHORT).show();
}
});
EneterTrace.error("Open connection failed.", err);
}
}
});
在 onCreate 中启动线程:
anOpenConnectionThread.start();
打开连接代码以防万一:
private void openConnection() throws Exception
{
// Create sender sending MyRequest and as a response receiving MyResponse
IDuplexTypedMessagesFactory aSenderFactory = new DuplexTypedMessagesFactory();
mySender = aSenderFactory.createDuplexTypedMessageSender(MyResponse.class, MyRequest.class);
// Subscribe to receive response messages.
mySender.responseReceived().subscribe(myOnResponseHandler);
// Create TCP messaging for the communication.
ip = sProfile.getIp();
IMessagingSystemFactory aMessaging = new TcpMessagingSystemFactory();
IDuplexOutputChannel anOutputChannel
= aMessaging.createDuplexOutputChannel("tcp://" + ip + ":8060/");
Toast.makeText(this, ip, Toast.LENGTH_SHORT).show();
// Attach the output channel to the sender and be able to send
// messages and receive responses.
mySender.attachDuplexOutputChannel(anOutputChannel);
}
sProfile 已初始化!这是设置 ip 的地方(它在 toast 中显示 ip,所以我 100% 确定它不为空)
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
int pos = profileSpinner.getSelectedItemPosition() + 1;
currentIp = myDb.getIp(pos);
Toast.makeText(SelectProfile.this, currentIp, Toast.LENGTH_SHORT).show();
}
getIp 正在返回其中设置的 ip。
public String getIp()
{
return currentIp;
}