UDP套接字接收不在后台服务中工作

时间:2014-02-16 21:15:35

标签: java android sockets service udp

我需要在后台服务中创建一个UDP套接字,以便随时接收数据包。我的类继承了Service并覆盖了onStartCommand():

public class NetworkListener extends Service
{
private DatagramSocket socket = null;
private int state = 0;

@Override
public void onCreate()
{
    super.onCreate();
}

@Override
public void onDestroy()
{
    super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    System.out.println("Here");
    if (intent != null)
    {
        System.out.println("Before while");
        byte[] buffer = new byte[50];   // Socket's buffer

        try {   socket = new DatagramSocket(4415);  }
        catch (SocketException e) {   e.printStackTrace();    }

        DatagramPacket data = new DatagramPacket(buffer, buffer.length);    // Receiving packet

        while (this.state == 0)
        {
            try {   socket.receive(data);   }
            catch (IOException e)   {   e.printStackTrace();    }
            System.out.println("In while");
            try {   parse(data);    }
            catch (UnsupportedEncodingException e)  {   e.printStackTrace();    }
        }
        socket.close();
    }
    return Service.START_STICKY;
}

当我执行代码时,我收到此错误:

java.lang.RuntimeException: Unable to start service com.example.electricfeel.NetworkListener@41e8a588 with Intent { cmp=com.example.electricfeel/.NetworkListener }: java.lang.NullPointerException

 Caused by: java.lang.NullPointerException
        at com.example.electricfeel.NetworkListener.onStartCommand(NetworkListener.java:53)

相关的是这一行:

 try {   socket.receive(data);   }

这就是我在HomeActivity中启动服务的方式:

this.m_networkListenerService = new Intent(this, NetworkListener.class);
this.startService(this.m_networkListenerService);

我的代码有什么问题?谢谢!

编辑:确定它已修复。我忘记将此行添加到我的AndroidManifest.xml文件中:

<uses-permission android:name="android.permission.INTERNET"/> 

但现在又出现了另一个错误:

Caused by: android.os.NetworkOnMainThreadException 
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)

据我所知,这是因为我在一个主线程上,因此不允许执行此类操作......

0 个答案:

没有答案