如何解决socket实例化错误?

时间:2014-02-28 03:48:59

标签: android

我尝试通过wifi连接android到打印机,我收到错误NetworkOnMainThreadException

这是我的代码:

public void OnClickPrint(View paramView) {  
    File file = new File(DB_PATH);
    try {
    Socket  client = new Socket("172.230.1.16", 9100);

        byte[] mybytearray = new byte[(int) file.length()]; 

        fileInputStream = new FileInputStream(file);
        bufferedInputStream = new BufferedInputStream(fileInputStream);

        bufferedInputStream.read(mybytearray, 0, mybytearray.length);                                                                   
        outputStream = client.getOutputStream();

        outputStream.write(mybytearray, 0, mybytearray.length); //
        outputStream.flush();
        bufferedInputStream.close();
        outputStream.close();
        client.close();

    } catch (UnknownHostException e) {
        Log.v("a", e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        Log.v("a", e.getMessage());
        e.printStackTrace();
    }
}

当我通过F6跟踪代码时,我在Socket client = new Socket("172.230.1.16", 9100);实例化时出现错误172.230.1.16是我的打印机IP。

错误logcat:

    02-28 09:44:40.572: E/AndroidRuntime(1426): FATAL EXCEPTION: main
    02-28 09:44:40.572: E/AndroidRuntime(1426): java.lang.IllegalStateException: Could not execute method of the activity
    02-28 09:44:40.572: E/AndroidRuntime(1426): at android.view.View$1.onClick(View.java:3044)
    02-28 09:44:40.572: E/AndroidRuntime(1426): at android.view.View.performClick(View.java:3511)
    02-28 09:44:40.572: E/AndroidRuntime(1426): at android.view.View$PerformClick.run(View.java:14105)
    02-28 09:44:40.572: E/AndroidRuntime(1426): at android.os.Handler.handleCallback(Handler.java:605)
    02-28 09:44:40.572: E/AndroidRuntime(1426): at android.os.Handler.dispatchMessage(Handler.java:92)
    02-28 09:44:40.572: E/AndroidRuntime(1426): at android.os.Looper.loop(Looper.java:137)
    02-28 09:44:40.572: E/AndroidRuntime(1426): at android.app.ActivityThread.main(ActivityThread.java:4424)
    02-28 09:44:40.572: E/AndroidRuntime(1426): at java.lang.reflect.Method.invokeNative(Native Method)
    02-28 09:44:40.572: E/AndroidRuntime(1426): at java.lang.reflect.Method.invoke(Method.java:511)
    02-28 09:44:40.572: E/AndroidRuntime(1426): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    02-28 09:44:40.572: E/AndroidRuntime(1426): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    02-28 09:44:40.572: E/AndroidRuntime(1426): at dalvik.system.NativeStart.main(Native Method)
    02-28 09:44:40.572: E/AndroidRuntime(1426): Caused by: java.lang.reflect.InvocationTargetException
    02-28 09:44:40.572: E/AndroidRuntime(1426): at  java.lang.reflect.Method.invokeNative(Native Method)
    02-28 09:44:40.572: E/AndroidRuntime(1426): at java.lang.reflect.Method.invoke(Method.java:511)
    02-28 09:44:40.572: E/AndroidRuntime(1426): at android.view.View$1.onClick(View.java:3039)
    02-28 09:44:40.572: E/AndroidRuntime(1426):     ... 11 more
    02-28 09:44:40.572: E/AndroidRuntime(1426): Caused by: android.os.NetworkOnMainThreadException
    02-28 09:44:40.572: E/AndroidRuntime(1426): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
    02-28 09:44:40.572: E/AndroidRuntime(1426): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
    02-28 09:44:40.572: E/AndroidRuntime(1426): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
    02-28 09:44:40.572: E/AndroidRuntime(1426): at libcore.io.IoBridge.connect(IoBridge.java:112)
    02-28 09:44:40.572: E/AndroidRuntime(1426): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
    02-28 09:44:40.572: E/AndroidRuntime(1426): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    02-28 09:44:40.572: E/AndroidRuntime(1426): at java.net.Socket.startupSocket(Socket.java:566)
    02-28 09:44:40.572: E/AndroidRuntime(1426): at java.net.Socket.tryAllAddresses(Socket.java:127)
    02-28 09:44:40.572: E/AndroidRuntime(1426): at java.net.Socket.<init>(Socket.java:177)
    02-28 09:44:40.572: E/AndroidRuntime(1426): at java.net.Socket.<init>(Socket.java:149)
    02-28 09:44:40.572: E/AndroidRuntime(1426):     at com.example.printertest.MainActivity.OnClickPrint(MainActivity.java:56)

如何解决?

1 个答案:

答案 0 :(得分:2)

  

引起:android.os.NetworkOnMainThreadException

您正在Android OS的主线程上执行网络操作。我建议你使用AsyncTask。 您应该在AsyncTask中执行长时间运行的网络操作。 AsyncTask可以正确,方便地使用UI线程。该类允许执行后台操作并在UI线程上发布结果,而无需操纵线程和/或处理程序。

public void OnClickPrint(View paramView) 
{ 
    new PrintFile().execute();
}

private class PrintFile extends AsyncTask<Void, Void, Void>
{
    @Override
    protected Void doInBackground(Void... result) 
    {
        File file = new File(DB_PATH);
        try {
        Socket  client = new Socket("172.230.1.16", 9100);

            byte[] mybytearray = new byte[(int) file.length()]; 

            fileInputStream = new FileInputStream(file);
            bufferedInputStream = new BufferedInputStream(fileInputStream);

            bufferedInputStream.read(mybytearray, 0, mybytearray.length);                                                                   
            outputStream = client.getOutputStream();

            outputStream.write(mybytearray, 0, mybytearray.length); //
            outputStream.flush();
            bufferedInputStream.close();
            outputStream.close();
            client.close();

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}