(旧帖子)
我正在尝试使用一种方法在Android设备(而非仿真器)上发送字符串通过UDP
但该应用程序无法正常工作,我也不知道为什么。.也许有人有一个主意。
在Android list ist中,可以进行互联网设置。
提前致谢!
(最新帖子)
好的,代码可以正常工作,但是我不太确定静态变量是将变量赋给线程的最佳方法还是唯一方法。这只是我所知道的唯一解决方案。
有没有更专业的方法将变量传递给线程方法?
(PS:这确实是最好的论坛)
新的工作代码如下:
package com.example.androidudp_client;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
private Button button1;
public EditText editText1;
public static String sendingWord = "";
// Method to send Sting to UDP Server
public static void sendToServer(String nachricht) throws SocketException, IOException, Exception, Throwable
{
DatagramSocket clientSocket = new DatagramSocket();
InetAddress ipaddr = InetAddress.getByName("192.168.178.65");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = nachricht;
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipaddr, 8888);
clientSocket.send(sendPacket);
clientSocket.close();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);
editText1 = (EditText)findViewById(R.id.editText1);
}
@Override
public void onClick(View arg0) {
String stringEditText = editText1.getText().toString();
sendingWord = stringEditText;
Toast.makeText(getApplicationContext(), "In editText steht : " + stringEditText, Toast.LENGTH_SHORT).show();
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try
{
sendToServer(sendingWord);
sendingWord = "";
} catch (Exception e)
{
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
String hier2 = errors.toString();
Toast.makeText(getApplicationContext(), "Exception :" + hier2, Toast.LENGTH_LONG).show();
}
catch (Throwable th)
{
StringWriter errors = new StringWriter();
th.printStackTrace(new PrintWriter(errors));
String hier3 = errors.toString();
Toast.makeText(getApplicationContext(), "Throwable :" + hier3, Toast.LENGTH_LONG).show();
}
}
});
thread.start();
}
}
最佳答案
我看到您只在捕获IOExceptions。
它可能是由SecurityException引起的。您可以将“IOException”更改为“Exception”,并查看引发了什么类型的异常。
注意:添加了此答案,因为它可以修复