2013-12-19 173 views
-2

我是android新手。我的項目與網絡有關。我收到此錯誤 致命異常:主要主線程致命異常

android.os.NetworkOnMainThreadException 
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java1133) 

... ...

我的代碼是:

package com.example.simpleclientactivity; 
    import java.io.IOException; 
    import java.io.PrintWriter; 
    import java.net.Socket; 
    import java.net.UnknownHostException; 

    import android.app.Activity; 
    import android.content.Context; 
    import android.os.Bundle; 
    import android.view.View; 
    import android.widget.Button; 
    import android.widget.EditText; 
    import android.widget.Toast; 

    public class SimpleClientActivity extends Activity { 

    private Socket client; 
    private PrintWriter printwriter; 
    private EditText textField1; 
    private Button button; 
    private String messsage; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     textField1 = (EditText) findViewById(R.id.editText1); //reference to the text field 
     button = (Button) findViewById(R.id.button1); //reference to the send button 

     //Button press event listener 
     button.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View v) { 

      Context context = getApplicationContext(); 
      CharSequence text = "Hello toast!"; 
      int duration = Toast.LENGTH_SHORT; 

      Toast toast = Toast.makeText(context, text, duration); 
      toast.show(); 
      messsage = textField1.getText().toString(); //get the text message on the text field  
      textField1.setText("");  //Reset the text field to blank 

      try { 

       client = new Socket("10.0.2.2", 4444); //connect to server 
       printwriter = new PrintWriter(client.getOutputStream(),true); 
       printwriter.write(messsage); //write the message to output stream 

       printwriter.flush(); 
       printwriter.close(); 
       client.close(); //closing the connection 

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

    } 
    } 

這裏的main.xml代碼

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context=".MainActivity" > 

    <EditText 
     android:id="@+id/editText1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"`enter code here` 
     android:layout_alignParentTop="true" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="83dp" 
     android:ems="10" 
     android:text="Client" > 

     <requestFocus /> 
    </EditText> 

    <Button 
     android:id="@+id/button1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/editText1" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="53dp" 
     android:text="Send" /> 

</RelativeLayout> 

點擊按鈕後,它甚至不顯示吐司消息。但它在android.os.NetworkOnMainThreadException中顯示錯誤。

+1

你無法通過'UI'連接到互聯網線程,使用'AsyncTask'類 –

+0

將套接字代碼移動到線程或異步腳本。 – Raghunandan

+1

它會花費更少的時間搜索答案,然後發佈此問題... – Vikram

回答

1

試試這個..當應用程序試圖在其主線程

進行聯網操作

,拋出此異常

button.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View v) { 

      Context context = getApplicationContext(); 
      CharSequence text = "Hello toast!"; 
      int duration = Toast.LENGTH_SHORT; 

      Toast toast = Toast.makeText(context, text, duration); 
      toast.show(); 
      messsage = textField1.getText().toString(); //get the text message on the text field  
      textField1.setText("");  //Reset the text field to blank 

      new MyClass().execute(messsage); 


     } 
     }); 

MyClass.class的AsyncTask

class MyClass extends AsyncTask<String, Void, String> { 

    private Exception exception; 

    protected String doInBackground(String... messsage) { 
     try { 

       client = new Socket("10.0.2.2", 4444); //connect to server 
       printwriter = new PrintWriter(client.getOutputStream(),true); 
       printwriter.write(messsage); //write the message to output stream 

       printwriter.flush(); 
       printwriter.close(); 
       client.close(); //closing the connection 

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

    protected void onPostExecute(String result) { 
     // TODO: check this.exception 
     // TODO: do something with the feed 
    } 
} 

您無法在Honeycomb上的UI線程上執行網絡IO。從技術上講,它可能在早期版本的Android上,但這是一個非常糟糕的主意,因爲它會導致您的應用程序停止響應,並可能導致操作系統因操作不當而導致您的應用程序死機。您需要運行後臺進程或使用AsyncTask在後臺線程上執行網絡事務。

在Android開發人員網站上有一篇關於Painless Threading的文章,對此進行了很好的介紹,並且會爲您提供比現實中提供的更好的深度。

0

你必須把你的代碼,訪問一個線程的互聯網

new Thread(new Runnable(){ 
    @Override 
    public void run(){ 
    //your code that access internet here 
    } 
}).start(); 
0

試試這個代碼

package com.example.simpleclientactivity; 
    import java.io.IOException; 
    import java.io.PrintWriter; 
import java.net.Socket; 
import java.net.UnknownHostException; 

import android.app.Activity; 
import android.content.Context; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 

public class SimpleClientActivity extends Activity { 

private Socket client; 
private PrintWriter printwriter; 
private EditText textField1; 
private Button button; 
private String messsage; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    textField1 = (EditText) findViewById(R.id.editText1); //reference to the text field 
    button = (Button) findViewById(R.id.button1); //reference to the send button 

    //Button press event listener 
    button.setOnClickListener(new View.OnClickListener() { 

    public void onClick(View v) { 

     Context context = getApplicationContext(); 
     CharSequence text = "Hello toast!"; 
     int duration = Toast.LENGTH_SHORT; 

     Toast toast = Toast.makeText(context, text, duration); 
     toast.show(); 
     messsage = textField1.getText().toString(); //get the text message on the text field  
     textField1.setText("");  //Reset the text field to blank 

    new GetCategory().execute(message); 
    } 
    }); 

} 


    //add inner class 

    class GetCategory extends AsyncTask<Void, Void, ArrayList<AbstractDetail>>{ 



    protected ArrayList<AbstractDetail> doInBackground(String... messsage) { 
     try { 

      client = new Socket("10.0.2.2", 4444); //connect to server 
      printwriter = new PrintWriter(client.getOutputStream(),true); 
      printwriter.write(messsage); //write the message to output stream 

      printwriter.flush(); 
      printwriter.close(); 
      client.close(); //closing the connection 

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

    } 

    protected void onPostExecute(ArrayList<AbstractDetail> result) 
    { 


     } 

    } 


} 






} 
0

問題

解決方案

  • 在該Thread.
  • 使用AsyncTask做網絡相關的工作創建新的線程和訪問網絡上的UI線程訪問網絡doInBackgroung()和用於更新UI onPostExecute()