DatagramSocket广播使用 附HandleThread使用

发送广播的类

package com.example.socketsendbroadcast;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.app.Activity;
import android.util.Log;

public class SocketSendBroadActivity extends Activity {
	protected static final String TAG = "SocketSendBroadActivity";
	private Handler mHandler;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.v(TAG, "onCreate");
		setContentView(R.layout.activity_socket_send_broad);
		//通过Handler启动线程  
        HandlerThread handlerThread = new HandlerThread("threadsendbroad");
        handlerThread.start();
        mHandler =  new Handler(handlerThread.getLooper());
        mHandler.post(mRunnable);  
	}

	private Runnable mRunnable = new Runnable() {  
        
        public void run() {
        	Log.v(TAG, "run...");
        	try {
        		sendBroadcast();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }  
          
    };  
	public static void sendBroadcast()throws Exception{
		Log.v(TAG, "sendBroadcast");
		DatagramSocket socket;
		DatagramPacket packet;
		byte[] data = "helloworld".getBytes();
		
		socket = new DatagramSocket();
		socket.setBroadcast(true);
		packet = new DatagramPacket(data,data.length,InetAddress.getByName("255.255.255.255"),8600);	//指定端口8600
		for(int i = 0 ; i < 20 ; i++){
			Thread.sleep(2000);
			socket.send(packet);
		}
	}
}

接受广播的类

package com.example.socketreceiverbroadcase;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;

public class SocketReceiverBroadcastActivity extends Activity {
	private static final String TAG = "SocketReceiverBroadcastActivity";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.v(TAG, "onCreate");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_socket_receiver_broadcast);
		Intent intent = new Intent();
		intent.setClass(this, ReceiverService.class);
		this.startService(intent);
	}

}


package com.example.socketreceiverbroadcase;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.util.Log;

public class ReceiverService extends Service{
	protected static final String TAG = "ReceiverService";
	private Handler mHandler;
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		//通过Handler启动线程  
        HandlerThread handlerThread = new HandlerThread("threadreceiverbroadcast");
        handlerThread.start();
        mHandler =  new Handler(handlerThread.getLooper());
        mHandler.post(mRunnable);  
	}

	private Runnable mRunnable = new Runnable() {  
        
        public void run() {
        	Log.v(TAG, "run...");
        	try {
				receiveBroadcast();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }  
          
    };  
    
	public static void receiveBroadcast()throws Exception{
		byte[] buffer = new byte[99];
		DatagramSocket server = new DatagramSocket(8600);
		DatagramPacket packet = new DatagramPacket(buffer , buffer.length);
		for(;;){
			Log.v(TAG, "receiveBroadcast");
			server.receive(packet);
			String s = new String(packet.getData( ), 0, packet.getLength( ));
			Log.v(TAG, "packet.getAddress = " + packet.getAddress() +
					" at port " + packet.getPort() +
					" get content " + s);
		}
	}
}

测试结果:

01-01 22:58:54.990: V/SocketReceiverBroadcastActivity(7138): onCreate
01-01 22:58:55.110: V/ReceiverService(7138): run...
01-01 22:58:55.120: V/ReceiverService(7138): receiveBroadcast
01-01 22:59:02.130: V/ReceiverService(7138): packet.getAddress = /192.168.30.106 at port 49869 get content helloworld
01-01 22:59:02.130: V/ReceiverService(7138): receiveBroadcast
01-01 22:59:04.180: V/ReceiverService(7138): packet.getAddress = /192.168.30.106 at port 49869 get content helloworld
01-01 22:59:04.180: V/ReceiverService(7138): receiveBroadcast
01-01 22:59:10.120: V/ReceiverService(7138): packet.getAddress = /192.168.30.106 at port 49869 get content helloworld
01-01 22:59:10.120: V/ReceiverService(7138): receiveBroadcast
01-01 22:59:12.160: V/ReceiverService(7138): packet.getAddress = /192.168.30.106 at port 49869 get content helloworld
01-01 22:59:12.160: V/ReceiverService(7138): receiveBroadcast
01-01 22:59:14.110: V/ReceiverService(7138): packet.getAddress = /192.168.30.106 at port 49869 get content helloworld
01-01 22:59:14.110: V/ReceiverService(7138): receiveBroadcast



你可能感兴趣的:(DatagramSocket广播使用 附HandleThread使用)