未发送Android数据报包:引发异常

时间:2015-07-02 10:13:44

标签: java android datagram

尝试将数据报包发送到服务器,当targetSdkVersion和compileSdkVersion设置为8(2.2)时,它会起作用。但是当我在将targetSdkVersion更改为22(5.1)(主题变为材质)后尝试执行相同操作时,问题就出现了。应用程序已安装但数据包未被发送,并且抛出了android.os.networkonmainthreadexception的异常。此外,服务器不会收到任何包。这是代码:

public void led(String s) throws Exception
{

    byte[] b=(s.getBytes());
    if(isOnline())
    {

    serverHostname1 = new String ("192.168.1.177");
    ip = InetAddress.getByName(serverHostname1);       
    d1 = new DatagramSocket();

    try{
        sendp =  new DatagramPacket(b,b.length, ip, 8032);
    }catch(Exception e){
        Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
    }

    try{
    d1.send(sendp);}
    catch(Exception e){         Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
    }
}
}

Build.gradle(模块)

apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
    applicationId "com.android.arduino"
    minSdkVersion 8
    targetSdkVersion 22
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_5
        targetCompatibility JavaVersion.VERSION_1_5
    }
}
productFlavors {
}
}
dependencies {
}

0 个答案:

没有答案