mina无法接udp数据包
发布网友
发布时间:2023-07-13 12:38
我来回答
共1个回答
热心网友
时间:2024-12-14 03:32
在做一个项目, 有一台android需要实时接受其它客户端的udp数据包(包括在锁屏的状态下), 我使用了mina框架, 在未锁屏的时候, 是能够正常的接受到数据包的, 但是一旦锁屏了就再也无法接受到数据包了, 直到唤醒屏幕。
以下是我service中的代码:
public class ListenerService extends Service {
private PowerManager.WakeLock mWakeLock;
private MINAServer server;
public static long lastMsgReceived = System.currentTimeMillis();
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.i("log_info", "ListenerService onCreate");
try {
server = new MINAServer();
} catch (IOException e) {
e.printStackTrace();
}
acquireWakeLock();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("log_info", "ListenerService onStartCommand");
// 启动一个定时器, 每隔32秒检测一次: lastMsgReceived 减去 当前时间。
Timer timer = new Timer();
timer.schele(new RecordConnTimes(), 0, 32 * 1000);
return super.onStartCommand(intent, flags, startId);
}
private void acquireWakeLock()
{
if (null == mWakeLock)
{
PowerManager pm = (PowerManager)this.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK| PowerManager.ON_AFTER_RELEASE,"");
if (null != mWakeLock)
{
mWakeLock.acquire();
}
}
}
@Override
public void onDestroy() {
if (null != mWakeLock)
{
mWakeLock.release();
mWakeLock = null;
}
super.onDestroy();
}
private class RecordConnTimes extends TimerTask {
@Override
public void run() {
Log.i("log_info", "RecordConnTimes run");
long currentTime = System.currentTimeMillis();
// 如果连续3次都没有接收到其它android端的广播, 则输出没有广播。
if (96 * 1000 <= currentTime - lastMsgReceived) {
Log.i("log_info", "大于等于3次没有接收到广播");
} else {
Message msg = new Message();
Bundle bundle = new Bundle();
Log.i("log_info", "小于3次没有接收到广播!!!");
}
}
}
}
下面是mina handler的messageReceived方法:
public void messageReceived(IoSession session, Object message)
throws Exception {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
Date curDate = new Date(System.currentTimeMillis()); //获取当前时间
if (message instanceof IoBuffer) {
IoBuffer buffer = (IoBuffer) message;
byte[] bb = buffer.array();
for (int i = 0; i < bb.length; i++) {
System.out.print((char) bb[i]);
}
System.out.println("");
System.out.println("");
IoBuffer buffer1 = IoBuffer.wrap("11".getBytes("UTF-8")); //返回信息给Clinet端
session.write(buffer1);
Log.i("log_info", "messageReceived, " + formatter.format(curDate));
}
// 一旦接受到广播就更新lastMsgReceived为当前时间
ListenerService.lastMsgReceived = System.currentTimeMillis();
}
请问我该怎么做才能让mina在锁屏的状态下也能接收到数据包呢? 还是说mina在android上达不到这样的要求呢。。?