package com.sunvote.xpadcomm; import android.os.Handler; import android.os.HandlerThread; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; import com.sunvote.util.LogUtil; /** * Created by Elvis on 2017/12/25 15:38 * Email:Eluis@psunsky.com * 版权所有:长沙中天电子设计开发有限公司 * Description: 人大通用版XPadAppRD * 下载文件发送数据请求线程 */ public class DownloadFileSendThread extends HandlerThread { private static String TAG = "DownloadFileSendThread" ; private DatagramSocket udpSocket ; private DatagramPacket packet; private Handler handler; public DownloadFileSendThread() { super(TAG); start(); handler = new Handler(getLooper()); } public boolean sendData(DatagramPacket packet){ this.packet = packet; handler.removeCallbacks(task); handler.post(task); return true; } private Runnable task = new Runnable() { @Override public void run() { if (handler != null) { handler.removeCallbacks(this); if (udpSocket == null) { try { udpSocket = new DatagramSocket(); } catch (SocketException e) { LogUtil.e(TAG, e); } } if (udpSocket != null && packet != null) { try { LogUtil.i(TAG,"send to server",packet.getData()); udpSocket.send(packet); } catch (IOException e) { LogUtil.e(TAG, e); udpSocket.close(); udpSocket = null; } } } if(handler != null){ handler.postDelayed(this, 1000); } } }; public void close(){ handler.removeCallbacks(task); if(udpSocket != null){ udpSocket.close(); udpSocket = null; } handler = null; packet = null; quit(); } }