Android:datagramsocket在后台(服务)不接收

时间:2014-07-20 14:23:32

标签: android multithreading service background datagram

我使用 DatagramSocket 在后台接收数据包(使用服务)。但是当我的手机被锁定时它没有收到,而当我每隔1秒添加 ScheduledTask 来启动线程时,它运行良好。为什么它在第一种情况下不起作用?我怎样才能在每1秒启动Tread的情况下修复它?

public class RecThread2 implements Runnable {

    public void run() {
      while(running){
        try {
            int MESSAGE_LEN = 60;
            byte[] recvBuffer = new byte[MESSAGE_LEN];
            DatagramPacket datagram = new DatagramPacket(recvBuffer,
                    MESSAGE_LEN);
            socket1.receive(datagram);
            String recvdString = new String(recvBuffer);
            Log.i("Recieved", recvdString);
            mess = recvdString;
        } catch (Exception e) {
            e.printStackTrace();
        }
      }
    }
}

我在这里运行线程:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "receiveTag");
    wl.acquire();

    Thread sThread2 = new Thread(new runSoc1());
    sThread2.start();

    return super.onStartCommand(intent, flags, startId);
}

但是,当我使用以下代码定期运行Thread时,即使手机被锁定(我从线程代码中删除while(running))也能正常工作:

        time = new Timer();
        ScheduledTask st = new ScheduledTask();
        time.schedule(st, 0, 1000);

和:

public class ScheduledTask extends TimerTask {
    public void run() {
        Thread sThread2 = new Thread(new RecThread2());
        sThread2.start();
    }
} 

0 个答案:

没有答案