我从 OutputStreamWriter() 得到 android.os.NetworkOnMainThreadException 和另一个未知异常

I'm getting android.os.NetworkOnMainThreadException and another unknown exception from the OutputStreamWriter()

我收到了 NetworkOnMainThreadException 异常和来自 OutputStreamWriter() 的未知异常。此 class 负责通过 PHP 脚本 http://213.251.43.215/addContact.php 连接到 SQL 数据库,如果匹配,它将 return 来自数据库的值。它似乎没有连接成功。

包 com.example.a_phi.nowswap;

import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class EstablishConnection extends AsyncTask<String, Void, String>{

    StringBuilder sb = new StringBuilder();

    public String doInBackground(String... id) {

        String link = "http://213.251.43.215/addContact.php";

        try {
            URL url = new URL(link);
            String data = URLEncoder.encode("id", "UTF-8")
                    + "=" + URLEncoder.encode(id[0], "UTF-8");

            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();
            BufferedReader reader = new BufferedReader(new
                    InputStreamReader(conn.getInputStream()));

            String line;

            // Read Server Response
            while((line = reader.readLine()) != null) {
                sb.append(line);
                break;
            }

        }catch(MalformedURLException e) {
            System.out.print("MalformedURLException" + e.getMessage());
            e.printStackTrace();
        }
        catch(IOException e){
            System.out.print("IOException"+e.getMessage());
            e.printStackTrace();
        }

        return sb.toString();
}

}

飞行员class...

包 com.example.a_phi.nowswap;

import android.annotation.TargetApi;
import android.content.pm.PackageManager;
import android.nfc.NfcAdapter;
import android.nfc.tech.IsoDep;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.nfc.Tag;
import android.content.Intent;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class Pilot extends AppCompatActivity {

    private String mParentPath;
    // Incoming Intent
    private Intent mIntent;
    public Timer timer1 = new Timer();
    NfcAdapter nfcadapter;
    public String idReceived;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pilot);
        View buttonPersonal = findViewById(R.id.buttonPersonal);
        View buttonProfessional = findViewById(R.id.buttonProfessional);
        View buttonUserGuide = findViewById(R.id.userGuide);
        //phone is put into reader mode to prevent android beam interfering
        enableReaderMode();
        //executes createContact() method periodically every second to refresh
        getData accessGetData = new getData();
        timer1.schedule(new TimerTask() {
            @Override
            public void run() {
                createContact();
            }
        }, 500, 500);




        PackageManager pm = this.getPackageManager();
        if(!pm.hasSystemFeature(PackageManager.FEATURE_NFC)) {
            Toast.makeText(this, "The device does not have NFC hardware.",
                    Toast.LENGTH_SHORT).show();
        } else if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
            Toast.makeText(this, "Android Beam is not supported.",
                    Toast.LENGTH_SHORT).show();
        }

            buttonPersonal.setOnClickListener(new View.OnClickListener(){

                public void onClick(View v){
                    Intent loadPersonal = new Intent(Pilot.this, personalHome.class);
                        startActivity(loadPersonal);

                }
            });

        buttonProfessional.setOnClickListener(new View.OnClickListener(){

            public void onClick(View v){
                Intent loadProfessional = new Intent(Pilot.this, professionalHome.class);
                startActivity(loadProfessional);
            }

        });


    }



    private byte[] selectApdu(byte[] aid) {
        byte[] commandApdu = new byte[6 + aid.length];
        commandApdu[0] = (byte)0x00; //CLA
        commandApdu[1] = (byte)0xA4; //INS
        commandApdu[2] = (byte)0x04; //P1
        commandApdu[3] = (byte)0x00; //P2
        commandApdu[4] = (byte)(aid.length & 0xFF); //Lc
        System.arraycopy(aid, 0, commandApdu, 5, aid.length); //DATA
        commandApdu[commandApdu.length - 1] = (byte)0x00; //Le
        return commandApdu;
    }



    /**enableReaderMode essentially turns off services such as Android Beam and ensures the device only READS nfc tags
     * allowing a smoother user interaction
     */
    @TargetApi(19)
    private void enableReaderMode() {
        nfcadapter = NfcAdapter.getDefaultAdapter(this);
        Bundle options = new Bundle();
        options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 5000);
        nfcadapter.enableReaderMode(this, new NfcAdapter.ReaderCallback() {
            @Override
            public void onTagDiscovered(Tag tag) {
                System.out.println("NFC onTagDiscovered " + tag.toString());
                IsoDep isoDep = IsoDep.get(tag);
                if (isoDep != null) {
                    try {
                        isoDep.connect();
                        //SelectAID command is sent to phone with HCE
                        byte[] result = isoDep.transceive(selectApdu(SelectAID));
                        idReceived = new String(result, "US-ASCII");
                        System.out.println("s outputs this "+ idReceived.substring(0,10));
                        idReceived = idReceived.substring(0,10);
                        checkProfile();
                        isoDep.close();
                        EstablishConnection accessEC = new EstablishConnection();
                        System.out.println("hello");
                        System.out.println("Dataset is "+accessEC.doInBackground(idReceived));
                    } catch(IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            isoDep.close();
                        } catch(Exception ignored) {}
                    }
                }
            }
        }, NfcAdapter.FLAG_READER_NFC_A | NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK,
                options);
    }

    public String getIdReceived(){
        return idReceived;
    }

    public void checkProfile(){
        getData accessGetData = new getData();
     //   System.out.println("hashlist value is "+accessGetData.doInBackground());
    }


    public static byte[] SelectAID = new byte[]{ (byte) 0xF2, (byte) 0x39, (byte) 0x85, (byte) 0x63,
            (byte) 0x24, (byte) 0x89, (byte) 0x73};

    public void createContact() {

        File newContact = new File("/storage/emulated/0/beam/", "personalInfoC.txt");

        /**there is a glitch on android beam with the file naming - sometimes it calls the file professionalInfoC.txt
        and other times professionalInfoC-0.txt **/
        if(!newContact.exists()) {
            newContact = new File("/storage/emulated/0/beam", "personalInfoC-0.txt");
            if(!newContact.exists()){
                File newContactProf = new File("/storage/emulated/0/beam", "professionalInfoC.txt");
                if(newContactProf.exists()){
                    //new activity will only be loaded if the file exists
                    Intent loadNewContact = new Intent(Pilot.this, receivedContact.class);
                    finish();
                    timer1.cancel();
                    startActivityForResult(loadNewContact, 1);

                }
                else if(!newContactProf.exists()){
                    newContactProf = new File("/storage/emulated/0/beam", "professionalInfoC-0.txt");
                    if(newContactProf.exists()) {
                        Intent loadNewContact = new Intent(Pilot.this, receivedContact.class);
                        finish();
                        timer1.cancel();
                        startActivityForResult(loadNewContact, 1);

                    }
                }
            }
        }
    };




}

这是堆栈跟踪

   07-19 00:53:14.436 13679-13692/com.example.a_phi.nowswap W/System.err: android.os.NetworkOnMainThreadException
              at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1315)
      07-19 00:53:14.437 13679-13692/com.example.a_phi.nowswap W/System.err:     at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:333)
              at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
              at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
              at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
              at java.net.Socket.connect(Socket.java:592)
              at com.android.okhttp.internal.Platform.connectSocket(Platform.java:113)
              at com.android.okhttp.Connection.connectSocket(Connection.java:196)
              at com.android.okhttp.Connection.connect(Connection.java:172)
              at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:367)
              at com.android.okhttp.OkHttpClient.connectAndSetOwner(OkHttpClient.java:130)
              at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:329)
              at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:246)
              at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457)
              at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:126)
              at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:257)
              at com.example.a_phi.nowswap.EstablishConnection.doInBackground(EstablishConnection.java:29)
              at com.example.a_phi.nowswap.Pilot.onTagDiscovered(Pilot.java:121)
              at android.nfc.NfcActivityManager.onTagDiscovered(NfcActivityManager.java:450)
              at android.nfc.IAppCallback$Stub.onTransact(IAppCallback.java:83)
              at android.os.Binder.execTransact(Binder.java:565)

如何解决这个问题?任何帮助将不胜感激。

在您的 enableReaderMode() 方法中调用 AsyncTask 对象的执行方法。

EstablishConnection accessEC = new EstablishConnection();
                        System.out.println("hello");
                        System.out.println("Dataset is "+accessEC.execute(idReceived));

您正在直接调用 accessEC.donInBackground(idReceived),它在当前(主)线程中运行该方法。