我正在开发一款需要扫描条形码的应用程序,然后通过TCPip端口将其发送到C#服务器。单个应用程序工作,但当我尝试读取变量并用于显示并发送它时(变量在扫描完成时更新)。 收到此错误:
致命的例外:主要 处理:com.example.android.miniclient,PID:11351 java.lang.RuntimeException:传递结果失败 ResultInfo {who = null,request = 0,result = -1,data = Intent { act = com.google.zxing.client.android.SCAN flg = 0x80000(有额外内容)}} 活动 {com.example.android.miniclient / com.example.android.miniclient.MainActivity}: android.os.NetworkOnMainThreadException
从读者应用程序中读取的代码:
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
//get the extras that are returned from the intent
contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
Toast toast = Toast.makeText(this, "Código Leido:" + contents + " Formato:" + format, Toast.LENGTH_LONG);
//connectSocket("Hello");
toast.show();
}
}
}
TCPip通信代码:
public void connectSocket(String a){
try {
InetAddress serverAddr = InetAddress.getByName("192.168.1.223");
Log.d("TCP", "C: Connecting...");
Socket socket = new Socket(serverAddr, 11000);
a="contents";
String message = a;
PrintWriter out = null;
BufferedReader in = null;
try {
更新代码显示已加入的代码:
public void updateTextView (String finalText) {
textView4.setText(finalText);
return;
}
我准备尝试从其他公共空间更新TextView,也尝试更改更新变量的时刻。但保持同样的问题。阅读器也单独工作,服务器/用户独立工作。
我需要扫描结果显示,并且以前称为变量。
感谢您的帮助
答案 0 :(得分:0)
您无法在Main(UI)线程上处理网络逻辑。如你所见,你得到了这个NetworkOnMainThreadException。
因此您无法在UI线程上运行此方法: public void connectSocket(String a){
try {
InetAddress serverAddr = InetAddress.getByName("192.168.1.223");
Log.d("TCP", "C: Connecting...");
Socket socket = new Socket(serverAddr, 11000);
a="contents";
String message = a;
PrintWriter out = null;
BufferedReader in = null;
try {
在Android文档中阅读更多相关内容: https://developer.android.com/training/basics/network-ops/connecting.html#AsyncTask
检查:
还有很多很好的库,比如:
BR!