【问题标题】:What is the error? New To Android Programming错误是什么? Android 编程新手
【发布时间】:2012-02-06 07:09:16
【问题描述】:

我正在尝试实现一个服务器客户端程序以在 Android 中发送消息。你能告诉我我的代码中有哪些错误以及如何纠正它们吗?服务器运行正常,但客户端程序有一个错误。

这是服务器代码,运行良好。

package com.app.MyServer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
public class MyServer extends Activity {
ServerSocket ss = null;
String mClientMsg = "";
Thread myCommsThread = null;
protected static final int MSG_ID = 0x1337;
public static final int SERVERPORT = 6000;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    TextView tv = (TextView) findViewById(R.id.TextView01);
    tv.setText("Nothing from client yet");
    this.myCommsThread = new Thread(new CommsThread());
    this.myCommsThread.start();
}
@Override
protected void onStop() {
    super.onStop();
    try {
            // make sure you close the socket upon exiting
            ss.close();
    } catch (IOException e) {
            e.printStackTrace();
    }
}
Handler myUpdateHandler = new Handler() {
    public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_ID:
                    TextView tv = (TextView) findViewById(R.id.TextView01);
                    tv.setText(mClientMsg);
                    break;
            default:
                    break;
            }
            super.handleMessage(msg);
    }
};
class CommsThread implements Runnable {
    public void run() {
            Socket s = null;
            try {
                    ss = new ServerSocket(SERVERPORT );
                    Log.v("SErver ",ss.toString());
            } catch (IOException e) {
                    e.printStackTrace();
            }
            while (!Thread.currentThread().isInterrupted()) {
                    Message m = new Message();
                    Log.v("Message ",m.toString());
                    m.what = MSG_ID;
                    try {
                            if (s == null && ss!=null)
                            {
                                s = ss.accept();
                                Log.v("Drrr","It is not null");
                            }
                            else
                                Log.v("The thing is ", "ss is null");

                            BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
                            String st = null;
                            st = input.readLine();
                            mClientMsg = st;
                            myUpdateHandler.sendMessage(m);
                    } catch (IOException e) {
                            Log.v("Error ",e.toString());
                            e.printStackTrace();
                    }
            }
    }
}
}

客户代码:

package com.exercise.AndroidClient;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AndroidClient extends Activity {

EditText textOut;
TextView textIn;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

 textOut = (EditText)findViewById(R.id.textout);
 Button buttonSend = (Button)findViewById(R.id.send);
 textIn = (TextView)findViewById(R.id.textin);
 buttonSend.setOnClickListener(buttonSendOnClickListener);
}

 protected class connect extends AsyncTask<String,DataInputStream,String>
 {



@Override
protected void onPreExecute() 
{
        Log.i( "makemachine", "onPreExecute()" );
     // TODO Auto-generated method stub
     Socket socket = null;
     DataOutputStream dataOutputStream = null;
     DataInputStream dataInputStream = null;

     try {
      socket = new Socket("10.0.2.2", 5000);
      dataOutputStream = new DataOutputStream(socket.getOutputStream());
      dataInputStream = new DataInputStream(socket.getInputStream());
      dataOutputStream.writeUTF(textOut.getText().toString());
      publishProgress(dataInputStream);

     }
     catch (UnknownHostException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
     catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
     finally
     {
      if (socket != null)
      {
       try {
        socket.close();
       }
       catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
      }

      if (dataOutputStream != null){
       try {
        dataOutputStream.close();
       } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
      }

      if (dataInputStream != null){
       try {
        dataInputStream.close();
       } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
      }
     }

        super.onPreExecute();

}

protected void onProgressUpdate(DataInputStream... dataInputStream) {
    Log.v("The mesage length is ",dataInputStream.toString());
    textIn.setText(dataInputStream.toString());
}



@Override
protected void onPostExecute( String result ) 
{
        super.onPostExecute(result);

        Log.i( "connected", "onPostExecute(): " + result );

}

@Override
protected String doInBackground(String... params) {
    // TODO Auto-generated method stub
    return null;
}
 }
 Button.OnClickListener buttonSendOnClickListener
  = new Button.OnClickListener(){


 public void onClick(View arg0) 
 {

     Log.v("Sending the message ","to the server");
  }};
}

日志是:

 02-06 01:55:31.421: E/AndroidRuntime(582): FATAL EXCEPTION: main
 02-06 01:55:31.421: E/AndroidRuntime(582): android.os.NetworkOnMainThreadException
 02-06 01:55:31.421: E/AndroidRuntime(582):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at libcore.io.IoBridge.connect(IoBridge.java:112)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at java.net.Socket.startupSocket(Socket.java:566)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at java.net.Socket.tryAllAddresses(Socket.java:127)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at java.net.Socket.<init>(Socket.java:177)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at java.net.Socket.<init>(Socket.java:149)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at com.exercise.AndroidClient.AndroidClient$1.onClick(AndroidClient.java:45)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at android.view.View.performClick(View.java:3511)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at android.view.View$PerformClick.run(View.java:14105)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at android.os.Handler.handleCallback(Handler.java:605)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at android.os.Handler.dispatchMessage(Handler.java:92)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at android.os.Looper.loop(Looper.java:137)
 02-06 01:55:31.421: E/AndroidRuntime(582):     at android.app.ActivityThread.main(ActivityThread.java:4424)
02-06 01:55:31.421: E/AndroidRuntime(582):  at java.lang.reflect.Method.invokeNative(Native Method)
02-06 01:55:31.421: E/AndroidRuntime(582):  at java.lang.reflect.Method.invoke(Method.java:511)
02-06 01:55:31.421: E/AndroidRuntime(582):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
02-06 01:55:31.421: E/AndroidRuntime(582):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
02-06 01:55:31.421: E/AndroidRuntime(582):  at dalvik.system.NativeStart.main(Native Method)

我读到我们无法在 UI 线程中实现网络线程。这就是我使用 AsyncTask 线程的原因。但即使这样我也得到 NetworkOnMainThread 异常。请告诉我程序中的错误以及如何纠正它们。

【问题讨论】:

    标签: java android networking exception-handling android-emulator


    【解决方案1】:
    That is why I am using the AsyncTask thread.But even then I get the NetworkOnMainThread Exception.
    

    实际上你不是。你需要调用execute()而不是直接调用doInBackground(),否则你没有使用AsyncTask提供的任何管道,你只是直接在UI中调用方法线程。

    【讨论】:

    • 仅供参考,您可以在行前添加&gt; 来引用。这将摆脱随机代码亮点
    • 对不起,如果我听起来很基本......你能说得更清楚吗?我应该删除 doInBackground() 吗?然后调用execute()?
    • @Sanjay D 我已经更改了代码并将它们放入 Preexecute。这种方法正确吗?
    • 我已经更改了代码并运行了它。现在它运行没有任何错误。但是消息仍然没有发送到客户端。谁能告诉我仍然是什么错误?
    【解决方案2】:

    你在做 textIn.setText(dataInputStream.readUTF());

    在 doInBackground() 方法中。而 doInBackground 应该只包含不属于事件线程的操作,所以,使用

    发布进度(参数);实现这一目标。

    【讨论】:

    • 我已经更改并更新了它。现在它运行没有任何错误。但是消息没有发送。你能告诉我还有什么错误吗?
    • 您只需要在 doInBackground 中执行此操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多