在我的代码中
public void vodKeyCtrl(byte[] sendDataByte, int send_length) {
try {
Log.i(TAG, addr.toString());
InetAddress ia = InetAddress.getByName(addr.getKeyIp());
DatagramSocket socket = new DatagramSocket(0);
socket.connect(ia, addr.getKeyPort());
DatagramPacket dp = new DatagramPacket(sendDataByte, sendDataByte.length);
socket.send(dp);
socket.setSendBufferSize(sendDataByte.length);
socket.close();
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
似乎没有错误和异常,它在JAVA Application上工作正常。虽然它只能在我的手机i9300上运行。我在
中更改了AndroidManifest.xml代码中的代码 <uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
代码<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
它只是工作得很好!!!我只是无法解决为什么这种情况发生了?
有人可以帮帮我吗?
答案 0 :(得分:1)
Fisrt of all确保您的舱单具有互联网许可
“uses-permission android:name =”android.permission.INTERNET“
然后在SDK8之后你必须使用这样的线程
public class MainActivity extends Activity implements OnClickListener
{
public static final String DEST_IP = "192.168.1.7";
public static final int DEST_UDP_PORT = 1234;
public static final byte[] buf = {'H','e','l','l','o',' ','U','D','P'};
public Button Send_UDP_Button;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Send_UDP_Button = (Button)findViewById(R.id.button1);
Send_UDP_Button.setOnClickListener(this);
}
@Override
public void onClick(View v)
{
new Thread(new Client()).start();
}
public class Client implements Runnable
{
@Override
public void run()
{
try
{
InetAddress serverAddr = InetAddress.getByName(DEST_IP);
DatagramSocket socket = new DatagramSocket();
DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, DEST_UDP_PORT);
socket.send(packet);
socket.close();
}
catch (Exception e)
{
Log.w("Too Bad",e);
}
}
}
}
我希望这会有所帮助! 抱歉无法投票你的问题我没有足够的声誉! : - (