[英]Android AsyncTask and networking mayham
我有一個連接到遠程聊天服務器的應用程序,然后用戶可以聊天。 我有一個表單,用戶在其中輸入主機名和端口,然后在另一個表單中,用戶查看所有消息並鍵入新消息。
對於網絡,似乎我別無選擇,只能使用AsyncTask。 但是有些事情我不知道該怎么做。 我會在調用onCreate()時在UI中啟動網絡連接,這不是問題。 但是,當我必須連接網絡和接口時,它變得一團糟。 我創建了兩個異步任務-一個用於發送,一個用於接收,但是它對我不起作用。 這是我首先啟動SenderTask的代碼,該代碼應該通過調用接收器任務開始通信,如果必須按下按鈕,則發送新消息:
public class Second extends Activity {
private SenderTask snd;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
// ...
final Button sendButton = (Button) findViewById(R.id.button2);
snd = new SenderTask();
snd.doInBackground(editTexts);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// when the button is clicked the next screen is loaded
snd.onProgressUpdate(true);
}
});
} // end of onCreate
}
然后是SenderTask類:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import android.os.AsyncTask;
import android.widget.EditText;
public class SenderTask extends AsyncTask<EditText, Boolean, Void> {
MulticastSocket so;
InetAddress serverAddress;
int port;
EditText eText1;
EditText eText2;
EditText eText3;
EditText messageBoard;
@Override
protected Void doInBackground(EditText... eTexts) {
eText1 = eTexts[0];
eText2 = eTexts[1];
eText3 = eTexts[2];
messageBoard = eTexts[3];
setUp();
return null;
}
private void setUp() {
// convert the host name to InetAddress
try {
//serverAddress = InetAddress.getByName(eText1.getText().toString());
serverAddress = InetAddress.getByName("my server name is here");
} catch (Exception e) {}
//convert the port to an int
//port = Integer.parseInt(eText2.getText().toString());
port = 4456;
// create socket and start communicating
try {
so = new MulticastSocket(port);
so.joinGroup(serverAddress);
} catch (IOException e) {}
// Start listening should be here
ReceiverTask rec = new ReceiverTask();
rec.doInBackground(messageBoard);
rec.onProgressUpdate(so);
}
private void sendMessage() {
// get the text that they contain and add the new messages to the old ones
String message = eText3.getText().toString();
String conversation = messageBoard.getText().toString();
String newConverstion = conversation.concat("\n[You] ").concat(message);
// make the messages text view editable
messageBoard.setFocusable(true);
messageBoard.setText(newConverstion); // add the new message to the text view
messageBoard.setFocusable(false); // make the messages text view not editable
// erase the text on the second text view that has just been sent
eText3.setText("");
// Send message to server
// convert message to bytes array
byte[] data = (message).getBytes();
// create and send a datagram
DatagramPacket packet = new DatagramPacket(data, data.length, serverAddress, port);
try {
so.send(packet);
} catch (IOException e) {}
} // end of sendMessage
protected void onProgressUpdate(boolean... go) {
if (go.equals(new Boolean(true))) {
sendMessage();
}
}
}
這是ReceiverTask類:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.MulticastSocket;
import android.os.AsyncTask;
import android.widget.EditText;
public class ReceiverTask extends AsyncTask<EditText, MulticastSocket, Void> {
MulticastSocket so;
EditText messageBoard;
@Override
protected Void doInBackground(EditText... messBo) {
messageBoard = messBo[0];
return null;
}
@Override
protected void onProgressUpdate(MulticastSocket... socket) {
so = socket[0];
byte[] data = new byte[1024]; // received data container
while (true) {
try {
// create a datagram for receivin
DatagramPacket packet = new DatagramPacket(data, data.length);
// wait for the next message
so.receive(packet);
String message = new String(data, 0, packet.getLength());
// add the new messages to the old ones
String conversation = messageBoard.getText().toString();
String newConverstion = conversation.concat("\n[Remote] ").concat(message);
// make the messages text view editable
messageBoard.setFocusable(true);
messageBoard.setText(newConverstion); // add the new message to the text view
messageBoard.setFocusable(false); // make the messages text view not editable
} catch (IOException ioe) {}
}
}
}
錯誤是:
01-25 14:26:09.739: E/AndroidRuntime(661): FATAL EXCEPTION: main
01-25 14:26:09.739: E/AndroidRuntime(661): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.regeduseroox.projx/com.regeduseroox.projx.Second}: java.lang.NullPointerException
01-25 14:26:09.739: E/AndroidRuntime(661): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
01-25 14:26:09.739: E/AndroidRuntime(661): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
01-25 14:26:09.739: E/AndroidRuntime(661): at android.app.ActivityThread.access$600(ActivityThread.java:123)
01-25 14:26:09.739: E/AndroidRuntime(661): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
01-25 14:26:09.739: E/AndroidRuntime(661): at android.os.Handler.dispatchMessage(Handler.java:99)
01-25 14:26:09.739: E/AndroidRuntime(661): at android.os.Looper.loop(Looper.java:137)
01-25 14:26:09.739: E/AndroidRuntime(661): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-25 14:26:09.739: E/AndroidRuntime(661): at java.lang.reflect.Method.invokeNative(Native Method)
01-25 14:26:09.739: E/AndroidRuntime(661): at java.lang.reflect.Method.invoke(Method.java:511)
01-25 14:26:09.739: E/AndroidRuntime(661): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-25 14:26:09.739: E/AndroidRuntime(661): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-25 14:26:09.739: E/AndroidRuntime(661): at dalvik.system.NativeStart.main(Native Method)
01-25 14:26:09.739: E/AndroidRuntime(661): Caused by: java.lang.NullPointerException
01-25 14:26:09.739: E/AndroidRuntime(661): at com.regeduseroox.projx.ReceiverTask.onProgressUpdate(ReceiverTask.java:33)
01-25 14:26:09.739: E/AndroidRuntime(661): at com.regeduseroox.projx.SenderTask.setUp(SenderTask.java:53)
01-25 14:26:09.739: E/AndroidRuntime(661): at com.regeduseroox.projx.SenderTask.doInBackground(SenderTask.java:27)
01-25 14:26:09.739: E/AndroidRuntime(661): at com.regeduseroox.projx.Second.onCreate(Second.java:38)
01-25 14:26:09.739: E/AndroidRuntime(661): at android.app.Activity.performCreate(Activity.java:4465)
01-25 14:26:09.739: E/AndroidRuntime(661): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
01-25 14:26:09.739: E/AndroidRuntime(661): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
01-25 14:26:09.739: E/AndroidRuntime(661): ... 11 more
ReceiverTask.java:33
是so.receive(packet);
SenderTask.java:53
是rec.onProgressUpdate(so);
SenderTask.java:27
是setUp();
Second.java:38
是snd.doInBackground(editTexts);
我不知道現在出了什么問題,我真的再也沒有解決該問題的想法。 任何幫助都感激不盡。
更換
snd.doInBackground(editTexts);
與
snd.execute(editTexts);
編輯
您不應直接調用onProgressUpdate()
或doInBackground()
來啟動AsyncTask,而應僅execute()
。 此外, onProgressUpdate()
在UI線程上完成其工作,實際上它僅用於更新ProgressBar
。 您應該將所有工作從onProgressUpdate()
移至doInBackground()
,並在onPostExecute()
返回數據。
我的建議是創建一個自定義類,其中將String
(會話)和MulticastSocket
(so)作為其字段。 在您的AsyncTask.execute()
調用中發送此對象,然后從varargs中檢索。
例如:
public class MyObject {
MulticastSocket so;
EditText messageBoard;
//... Getters and Setters omitted for brevity
}
然后在您的SenderTask中:
ReceiverTask rec = new ReceiverTask();
MyObject obj = new MyObject(so, messageBoard);
rec.execute(obj);
您應該對Second / SenderTask使用相同的想法(將工作從onProgressUpdate()
刪除)。
讓我知道這是否很清楚,請確保重新閱讀有關AsyncTask正確用法的文檔。
它說在Second.java中有一個NullPointerException。 在代碼中設置一個斷點,使用調試器,一步一步地遍歷代碼,然后查看斷點。 我不能從錯誤中告訴足夠多,但對我來說好像editText
可能為null
snd.doInBackground(editTexts);
另外,如果您使用多播套接字,則應該使用多播地址,而不是服務器的IP地址。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.