Android - 手机空闲无法捕获网络数据包

时间:2014-05-10 14:50:21

标签: android sockets networking udp

我已经编写了一个应用程序,其服务正在侦听传入的广播UDP数据包。它工作正常,在收到" OK"时启动一个活动,但是当手机空闲时(屏幕关闭),似乎服务停止收听数据包。只需打开屏幕即可再次正常工作。

服务并没有真正停止,我在其中放入了一些Log()命令,我可以在logcat中看到它仍然在运行。当屏幕关闭时,它无法捕获网络数据包。 为确保服务能够运行,我添加了一个startForeground()命令,但这并没有解决问题。 还尝试使用带有PARTIAL_WAKE_LOCK标志的wakelock.acquire()来保持CPU活动,但仍然无法正常工作。

当手机空闲时,系统中是否有任何内容可以阻止网络活动?我不这么认为。怎么做whatsapp,facebook,ecc ......?即使手机处于空闲状态,他们也可以在收到新消息时获取数据并进行通知。也许它们会启动客户端连接,而我需要监听传入的UDP数据包。

这是代码的摘录:

public class UDPlistener extends Service {
private DatagramSocket UDPsocket;
String result;
Intent myIntent;
PowerManager.WakeLock wakelock;

@Override
public void onCreate() {
Log.e("UDPlistener","onCreate");

Intent intent = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification noti = new Notification.Builder(this)
.setContentTitle("UDP listener")
.setContentText("UDP listener ")
.setContentIntent(pIntent)
.setSmallIcon(R.drawable.ic_launcher)
.build();
startForeground(1, noti);

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wakelock.acquire();

new Thread( new Runnable() {
@Override
public void run() {
  try {
  Log.i("UDPlistener","Start listening...");
  UDPsocket = new DatagramSocket(9999);
  byte[] receiveData = new byte[64];
  DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
  UDPsocket.receive(receivePacket);
  if (receiveData.length > 0) {
    result = new String(receivePacket.getData());
  } else {
    result = "";
  }

  if (result.length() > 1 && (result.substring(0,2)).equals("OK")) {
    //Start activity
    if (myIntent == null) {
      myIntent = new Intent(UDPlistener.this, UDPactivity.class);
      myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);
      }
    startActivity(myIntent);
  } 

  } catch (UnknownHostException e) {
    Log.e("UDPlistener","UnknownHostException");
    e.printStackTrace();
  } catch(SocketTimeoutException e) {
    Log.e("UDPlistener","SocketTimeoutException");
    //e.printStackTrace();
  } catch (SocketException e) {
    Log.e("UDPlistener","SocketException");
    e.printStackTrace();
  } catch (IOException e) {
    Log.e("UDPlistener","IOException");
    e.printStackTrace();
  } catch (Exception e) {
    Log.e("UDPlistener","Generic Exception");
    e.printStackTrace();
  } finally {
    UDPsocket.close();
  } //try
}
}).start();
super.onCreate();
} //onCreate


@Override
public void onDestroy() {
  Log.e("UDPlistener","onDestroy");
  UDPsocket.close();
  wakelock.release();
  super.onDestroy();
} //onDestroy

0 个答案:

没有答案