(旧帖) 我正在尝试使用一种方法通过UDP在Android设备(非模拟器)上发送字符串,但应用程序无法正常工作,我不知道为什么..也许有人有想法。
在Android清单中设置了Internet权限。
提前致谢!
(新帖) 好的,代码正在运行,但是我不确定静态变量是否是向线程传递变量的最佳或唯一方法。这只是我所知道的唯一解决方案。
是否有更专业的方法将变量传递给线程方法?
(附言:这真的是最好的论坛)
下面是新的工作代码:
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();
}
}