线程错误,初学者求助

qq_38795535 2018-01-07 12:53:33
package com.example.znju;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class SocketDemo extends Activity implements Runnable {
private TextView tv_msg = null;
private EditText ed_msg = null;
private Button btn_send = null;
private static final String HOST="localhost";
private static final int PROT=9999;
private Socket socket = null;
private BufferedReader in = null;
private PrintWriter out = null;
private String content="";
public Handler mHandler = new Handler(){
public void handleMessage(Message msg){
super.handleMessage(msg);
tv_msg.setText(content);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv_msg = (TextView)findViewById(R.id.textView2);
ed_msg = (EditText)findViewById(R.id.edit01);
btn_send = (Button) findViewById(R.id.button02);
setContentView(R.layout.activity_main);

try{
InetAddress serd =InetAddress.getByName(HOST);
socket = new Socket(serd,PROT);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
}catch (IOException ex){
ex.printStackTrace();
ShowDialog("login exception"+ex.getMessage());
}
btn_send.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
String msg = ed_msg.getText().toString();
if(socket.isConnected()){
if(!socket.isOutputShutdown()){
out.println(msg);
}
}
}
});
new Thread(SocketDemo.this).start();

}





public void ShowDialog(String msg){
new AlertDialog.Builder(this).setTitle("notification").setMessage(msg).setPositiveButton("ok",new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub

}
}).show();
}
public void run(){
try{
while(true){
if(!socket.isClosed()){
if(socket.isConnected()){
if(!socket.isInputShutdown()){
if((content=in.readLine())!=null){
content +="\n";
mHandler.sendMessage(mHandler.obtainMessage());
}else{

}
}
}
}
}
}catch (Exception e){
e.printStackTrace();
}
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}


}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.znju"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.znju.SocketDemo"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>


01-07 12:15:16.884: D/AndroidRuntime(2360): Shutting down VM
01-07 12:15:16.884: W/dalvikvm(2360): threadid=1: thread exiting with uncaught exception (group=0x94c43b20)
01-07 12:15:16.884: E/AndroidRuntime(2360): FATAL EXCEPTION: main
01-07 12:15:16.884: E/AndroidRuntime(2360): Process: com.example.znju, PID: 2360
01-07 12:15:16.884: E/AndroidRuntime(2360): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.znju/com.example.znju.SocketDemo}: android.os.NetworkOnMainThreadException
01-07 12:15:16.884: E/AndroidRuntime(2360): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2193)
01-07 12:15:16.884: E/AndroidRuntime(2360): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
01-07 12:15:16.884: E/AndroidRuntime(2360): at android.app.ActivityThread.access$800(ActivityThread.java:135)
01-07 12:15:16.884: E/AndroidRuntime(2360): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
01-07 12:15:16.884: E/AndroidRuntime(2360): at android.os.Handler.dispatchMessage(Handler.java:102)
01-07 12:15:16.884: E/AndroidRuntime(2360): at android.os.Looper.loop(Looper.java:136)
01-07 12:15:16.884: E/AndroidRuntime(2360): at android.app.ActivityThread.main(ActivityThread.java:5019)
01-07 12:15:16.884: E/AndroidRuntime(2360): at java.lang.reflect.Method.invokeNative(Native Method)
01-07 12:15:16.884: E/AndroidRuntime(2360): at java.lang.reflect.Method.invoke(Method.java:515)
01-07 12:15:16.884: E/AndroidRuntime(2360): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-07 12:15:16.884: E/AndroidRuntime(2360): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-07 12:15:16.884: E/AndroidRuntime(2360): at dalvik.system.NativeStart.main(Native Method)
01-07 12:15:16.884: E/AndroidRuntime(2360): Caused by: android.os.NetworkOnMainThreadException
01-07 12:15:16.884: E/AndroidRuntime(2360): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
01-07 12:15:16.884: E/AndroidRuntime(2360): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
01-07 12:15:16.884: E/AndroidRuntime(2360): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
01-07 12:15:16.884: E/AndroidRuntime(2360): at java.net.InetAddress.getByName(InetAddress.java:289)
01-07 12:15:16.884: E/AndroidRuntime(2360): at com.example.znju.SocketDemo.onCreate(SocketDemo.java:52)
01-07 12:15:16.884: E/AndroidRuntime(2360): at android.app.Activity.performCreate(Activity.java:5231)
01-07 12:15:16.884: E/AndroidRuntime(2360): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
01-07 12:15:16.884: E/AndroidRuntime(2360): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
01-07 12:15:16.884: E/AndroidRuntime(2360): ... 11 more


...全文
396 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
YXTS122 2018-02-19
  • 打赏
  • 举报
回复
不能在主线程进行操作呀!!!!!!!
bdmh 2018-01-08
  • 打赏
  • 举报
回复
SDK(3.0)开始,google不再允许网络请求(HTTP、Socket)等相关操作直接在Main Thread类中,所以你的网络链接应该放倒异步中,你可以使用一些第三方框架,比如netty
warcraftmgq 2018-01-08
  • 打赏
  • 举报
回复
充分说明了搞编程还是要学点英文的,至少可以大体看懂异常信息,有个头绪。
Jing丶無雙 2018-01-08
  • 打赏
  • 举报
回复
   try{
        	InetAddress serd =InetAddress.getByName(HOST);
        	socket = new Socket(serd,PROT);
        	in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        	out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
        }catch (IOException ex){
        	ex.printStackTrace();
        	ShowDialog("login exception"+ex.getMessage());
        }
这部分代码涉及到Socket请求,这是不能在UI线程直接执行的,需要写在子线程里面 01-07 12:15:16.884: E/AndroidRuntime(2360): Caused by: android.os.NetworkOnMainThreadException 01-07 12:15:16.884: E/AndroidRuntime(2360): at com.example.znju.SocketDemo.onCreate(SocketDemo.java:52) 这里的报错提示已经说得很清楚,你代码的第52行导致了该NetworkOnMainThreadException异常,这是网络请求在MainThread中产生的异常

80,350

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧