簡體   English   中英

嘗試從掃描程序加載信息時,Android應用程序崩潰

[英]Android App Crashes when try to load Info from Scanner

我正在開發一個應用程序,它需要掃描條形碼然后通過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(有額外內容)}}到activity {com.example.android.miniclient / com.example.android.miniclient.MainActivity}:android.os.NetworkOnMainThreadException

來自Android App的代碼,如下:

從閱讀器應用程序讀取的代碼:

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,也嘗試更改更新變量的時刻。 但保持同樣的問題。 閱讀器也單獨工作,服務器/用戶獨立工作。

我需要掃描結果顯示,並用於調用變量。

謝謝你的幫助

您無法在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!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM