A_lowB
A_lowB
2016-07-24 12:06
采纳率: 0%
浏览 1.8k

Android UDP发送广播消息的时候出了问题

在写一个程序,需要用到udp来广播本机的IP
于是我在启动的时候先设一个监听,等待udp广播,然后再设置一个button,按下button的时候就会在局域网内广播本机的ip地址。但是现在程序可以正常启动,监听也可以正常设置,但是一旦按下按钮程序就崩溃,求各位大神帮忙看一下小弟的程序错在哪里了好吗?

这是运行的时候的错误消息
07-24 08:00:08.083: E/AndroidRuntime(1537): android.os.NetworkOnMainThreadException
07-24 08:00:08.083: E/AndroidRuntime(1537): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
07-24 08:00:08.083: E/AndroidRuntime(1537): at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:175)
07-24 08:00:08.083: E/AndroidRuntime(1537): at libcore.io.IoBridge.sendto(IoBridge.java:466)
07-24 08:00:08.083: E/AndroidRuntime(1537): at java.net.PlainDatagramSocketImpl.send(PlainDatagramSocketImpl.java:182)
07-24 08:00:08.083: E/AndroidRuntime(1537): at java.net.DatagramSocket.send(DatagramSocket.java:284)
07-24 08:00:08.083: E/AndroidRuntime(1537): at com.example.testudp.UdpListener.SendMessage(UdpListener.java:39)
07-24 08:00:08.083: E/AndroidRuntime(1537): at com.example.testudp.MainActivity$2.onClick(MainActivity.java:49)

说明是datagramsocket.send()函数那里出了错误,可是为什么呢?

下面是UdpListener的代码:
package com.example.testudp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class UdpListener {
private int port = 9999;
private DatagramSocket ds = null;
private DatagramPacket dp = null;
private byte[] buf = new byte[1024]; //存储发来的消息
private StringBuffer sbuf ;

public UdpListener() {
    sbuf = new StringBuffer();
    try {
        ds = new DatagramSocket(port);
    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    dp = new DatagramPacket(buf, buf.length);
}


public String SendMessage(String msg) {
    String host = "255.255.255.255";        //广播地址
    String message = msg;

    try {
        InetAddress adds = InetAddress.getByName(host);
        DatagramSocket ds = new DatagramSocket();
        DatagramPacket dp = new DatagramPacket(message.getBytes(),
                message.length(), adds, port);
        ds.send(dp);
        ds.close();
    } catch (UnknownHostException e) {
        return e.getMessage();
    } catch (SocketException e) {
        return e.getMessage();
    } catch (IOException e) {
        return e.getMessage();
    }
    return "Success";
}

public String ReceiveMessage()
{
    sbuf.delete(0, sbuf.length());
    System.out.println("等待广播消息");
    try {
        ds.receive(dp);
        int i;
        for(i=0;i<1024;i++){
            if(buf[i] == 0){
                break;
            }
            sbuf.append((char) buf[i]);
        }
        System.out.println("收到广播消息:" + sbuf.toString());
    } catch (IOException e) {
        return e.getMessage();
    }
    return sbuf.toString();
}

}

下面是activity的代码
package com.example.testudp;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
private Button link;
private String message = null;
@SuppressWarnings("unused")
private EditText password;
private TextView txt;
private UdpListener ul;
private Handler handler;

@SuppressLint("HandlerLeak") @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    link = (Button)findViewById(R.id.link);
    txt = (TextView)findViewById(R.id.txt1);
    password = (EditText)findViewById(R.id.pass);
    ul = new UdpListener();


    handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what){
            case 0:
                txt.append(msg.obj.toString());
            }
        }
    };

    link.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View v) {
            ul.SendMessage(GetIpAddress());
            //Message.obtain(handler, 0, "1234").sendToTarget();
        }
    });

    Listener listener = new Listener();
    listener.start();
}



private class Listener extends Thread{
    @Override
    public void run(){

        Message.obtain(handler, 0, "本机IP" + GetIpAddress()).sendToTarget();
        Message.obtain(handler, 0, "等待消息").sendToTarget();
        while(true)
        {
            message = ul.ReceiveMessage();
            Message.obtain(handler, 0, "收到消息" + message).sendToTarget();
        }
    }
}

public String GetIpAddress() {     
    WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);     
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();     
    int i = wifiInfo.getIpAddress();
    return (i & 0xFF) + "." +     
           ((i >> 8 ) & 0xFF) + "." +     
           ((i >> 16 ) & 0xFF)+ "." +     
           ((i >> 24 ) & 0xFF );     
}

}

求大神告知为什么崩溃。。。万分感谢
ps:网络的权限和wifi的权限我都添加了

这是一开始的界面,点了button就会崩溃

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • devmiao
    devmiao 2016-07-24 15:53
    点赞 评论
  • lianjiao511214
    lianjiao511214 2017-09-13 03:04

    找到错误原因没,我找到了,但是解决方案还没。错误是因为Android SE有安全验证问题,如果你把255.255.255.255 IP地址换一下,换成具体的IP就不会出现这个问题了。非Android SE安全系统可以,有安全限制的,需要申请广播权限才能使用255.255.255.255

    点赞 评论

相关推荐