public class HeartBeatService extends Service implements Runnable {
private Thread mThread;
private HeartBeatMsg mHeartBeatMsg;
private DatagramSocket mDatagramSocket;
private DatagramPacket mDatagramPacket;
private String ServerIp;
private boolean isTip = true;
private boolean flag;
/**
* 本地端口
*/
private static int LOCALPORT = 57000;
/**
* 服务器端口
*/
private static int SERVERPORT = 37000;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
flag = true;
ServerIp = intent.getExtras().getString("serverIp");
mThread = new Thread(this);
mHeartBeatMsg = new HeartBeatMsg();
mHeartBeatMsg.setMonitorId(intent.getExtras().getInt("monitorId"));
try {
mDatagramSocket = new DatagramSocket(LOCALPORT);
mDatagramPacket = new DatagramPacket(mHeartBeatMsg.getByteData(),
13, InetAddress.getByName(ServerIp), SERVERPORT);
} catch (Exception e) {
e.printStackTrace();
}
mThread.start();
}
@Override
public void onDestroy() {
flag = false;
super.onDestroy();
}
@Override
public void run() {
int i = 0;
while (flag) {
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(3);
if ("cn.csv.mobileclient".equals(tasks.get(0).topActivity
.getPackageName())) {
isTip = true;
} else {
isTip = false;
}
if (isTip) {
try {
mDatagramSocket.send(mDatagramPacket);
LogUtil.d(this, "第" + i++ + "次发送心跳");
SystemClock.sleep(1000 * 10);
} catch (IOException e) {
e.printStackTrace();
}
} else {
stopService(new Intent(getApplicationContext(),
HeartBeatService.class));
}
}
}
}
心跳帧
最新推荐文章于 2024-06-17 15:26:07 发布