2012-12-03 97 views
3

我試圖將asynctask併入我的代碼中,因爲NetworkOnMainThreadException由於我在一分鐘內關閉了一個部隊。使用asynctask進行網絡連接

我已經經歷了一些教程,但仍然無法擺脫困境。每次我嘗試一下,我都會得到各地的錯誤。

教程我看着:

  1. [http://developer.android.com/reference/android/os/AsyncTask.html][1]
  2. [HTTPS://androidresearch.wordpress .COM/2012/03/17 /理解-的AsyncTask,一勞永逸的永遠/] [2]

基本上什麼代碼的作用是:

  1. 以一個IP地址FR一個意圖。
  2. 連接到帶有端口32的IP
  3. 然後發送一個命令,等待響應併發送另一個命令。
  4. 在我們發送了2個命令之後,我應該得到「SNX_COM>」的響應
  5. 建立連接後,我希望連接保持打開狀態,以便在單擊按鈕時發送特定命令。

^^這基本上是我的代碼應該達到^^

package com.smarte.smartipcontrol; 

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 java.net.UnknownHostException; 

import android.app.Activity; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.view.View; 

public class IPControl extends Activity { 

private Socket socket; 
private String serverIpAddress = "com.smarte.smartipcontrol.ACTU_IP"; 
private static final int REDIRECTED_SERVERPORT = 32; 
public PrintWriter out; 
public BufferedReader in; 
public String data; 
public Object pd; 



public void getModel(View view) { 
    try { 
     out.println("[m\r\n"); 
     //System.out.print("root\r\n"); 
     while(!in.ready()); 
     String textStatus = readBuffer(); 

    } catch(IOException e) {} 
} 


@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.act_ipcontrol); 


    try{ 

    new AsyncAction().execute(); 

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

    } 



private class AsyncAction extends AsyncTask<String, Void, String> { 
    protected String doInBackground(String... args) { 
    try { 
InetAddress serverAddr = InetAddress.getByName(serverIpAddress); 
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT); 
} catch (UnknownHostException e1) { 
e1.printStackTrace(); 
} catch (IOException e1) { 
e1.printStackTrace(); 
} 
try { 
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
while (! in .ready()); 
readBuffer(); 
out.println("root\r\n"); 
//System.out.print("root\r\n"); 
while (! in .ready()); 
readBuffer(); 
out.println("root\r\n"); 
//System.out.print("root\r\n"); 
while (! in .ready()); 
String msg = ""; 

while (in .ready()) { 
msg = msg + (char) in .read(); 
} 
} catch (IOException e) {} 

     return null;//returns what you want to pass to the onPostExecute() 
    } 

    protected void onPostExecute(String result) { 

    //results the data returned from doInbackground 

     IPControl.this.data = result; 



     } 
    } 


private String readBuffer() throws IOException { 
    String msg = ""; 

    while(in.ready()) { 
     msg = msg + (char)in.read(); 
    } 
    //System.out.print(msg); 
    if(msg.indexOf("SNX_COM> ") != -1) return msg.substring(0, msg.indexOf("SNX_COM> ")); 
    else return msg; 
} 

} 

logcat的

12-03 15:39:56.346: E/AndroidRuntime(2697): FATAL EXCEPTION: AsyncTask #5 
12-03 15:39:56.346: E/AndroidRuntime(2697): java.lang.RuntimeException: An error occured while executing doInBackground() 
12-03 15:39:56.346: E/AndroidRuntime(2697):  at android.os.AsyncTask$3.done(AsyncTask.java:299) 
12-03 15:39:56.346: E/AndroidRuntime(2697):  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352) 
12-03 15:39:56.346: E/AndroidRuntime(2697):  at java.util.concurrent.FutureTask.setException(FutureTask.java:219) 
12-03 15:39:56.346: E/AndroidRuntime(2697):  at java.util.concurrent.FutureTask.run(FutureTask.java:239) 
12-03 15:39:56.346: E/AndroidRuntime(2697):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
12-03 15:39:56.346: E/AndroidRuntime(2697):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
12-03 15:39:56.346: E/AndroidRuntime(2697):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
12-03 15:39:56.346: E/AndroidRuntime(2697):  at java.lang.Thread.run(Thread.java:856) 
12-03 15:39:56.346: E/AndroidRuntime(2697): Caused by: java.lang.NullPointerException 
12-03 15:39:56.346: E/AndroidRuntime(2697):  at com.smarte.smartipcontrol.IPControl$AsyncAction.doInBackground(IPControl.java:71) 
12-03 15:39:56.346: E/AndroidRuntime(2697):  at com.smarte.smartipcontrol.IPControl$AsyncAction.doInBackground(IPControl.java:1) 
12-03 15:39:56.346: E/AndroidRuntime(2697):  at android.os.AsyncTask$2.call(AsyncTask.java:287) 
12-03 15:39:56.346: E/AndroidRuntime(2697):  at java.util.concurrent.FutureTask.run(FutureTask.java:234) 
12-03 15:39:56.346: E/AndroidRuntime(2697):  ... 4 more 
+0

嗨,你可以嘗試this kumar

+0

顯示一些代碼,你實際使用的AsyncTask – Tim

+0

我已經請參閱更新代碼和LogCat,仍然有問題,我開始失去我的大理石-_- –

回答

1

你有你的createConnection();移動到您的AsyncTask的doInBackground(),你必須添加爲內課程或單獨的課程 例如:

private class DownloadFilesTask extends AsyncTask<Void, Void, Void> { 
protected Void doInBackground(Param[]...) { 
    createConnection(); 
} 

protected void onProgressUpdate() { 
    setProgressPercent(progress[0]); 
} 

protected void onPostExecute() { 


} 

}

這是從你提供的第一個鏈接我只是改變了一點點。確保你從法的createConnection(返回的東西),讓你知道的AsyncTask已成功或者未完成和改變DownloadFilesTask因此使doInBackground()onPostExecute()返回類型相同

+0

仍然出現錯誤。請參閱更新的代碼和logcat –

+0

第71行是什麼?愚蠢的問題 - 你把在清單 – vodich

+0

嗨感謝您的迴應,我已經修復了上述問題,但現在有一個新問題-_- –

1

一旦連接建立,我想連接在按鈕點擊時保持打開以發送特定命令。

您可能必須做出一個新的線程,當你想將命令發送到服務器:

button.setOnClickListener(new OnClickListener() 
{ 
    public void onClick(View arg0) 
    { 
     new Thread() 
     { 
     @Override 
     public void run() 
     { 
      methods.sendCommandToServer(); 
     } 
     }.start(); 
    } 
    });