Android网络应用程序运行服务

时间:2012-12-26 03:49:53

标签: android sockets networking service adb

我创建了一个运行后台服务的Android应用程序,该服务执行以下操作:

1)要求UDP服务器向其发送100个数据包

2)在while(true)循环中接收数据包

3)使用setSoTimeout使得接收在5分钟后超时并退出循环

每2分钟重复上述操作。当手机连接到PC并且使用adb logcat监控每个步骤时,应用程序完全正常,但当手机与PC断开连接时应用程序停止工作。然后在文件中记录每个步骤,表明最后一步是接收步骤,在此步骤之后套接字不会超时。可能的原因是什么?有没有其他方法可以让我以固定的间隔完成预定的任务? 这是从服务启动的线程的运行函数:

   public void downlink() 
{
    String path = extStorageDirectory + "/" + appFolder + "/REP_DT_" + Long.toString(System.currentTimeMillis()) + ".txt";
    File file = new File(path);
    if(!file.exists())
    try 
    {
        file.createNewFile();
    }
    catch (IOException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String p = extStorageDirectory + "/Goonj/logtput.txt";
    try {
        DatagramSocket clientSocket = new DatagramSocket();
        try {
            FileWriter fw = new FileWriter(path,true);
            fw.write("\n\n");
            fw.close();             
            clientSocket.setSoTimeout(120000);
            InetAddress IPAddress = InetAddress.getByName(IP);
            long id = System.currentTimeMillis();      
            byte[] sendData = createMessage(id,0,1400,150);     
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9010);
            clientSocket.send(sendPacket);      
            byte[] receiveData = new byte[10240];
            boolean flag = true;
            while(flag)//for(int i=0; i<100; i++)
            {      
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); 
                writeToLog(p,"START");
                clientSocket.receive(receivePacket);
                writeToLog(p,"END");
                long time = System.currentTimeMillis();
                String data = new String(receivePacket.getData(), 0, receivePacket.getLength());
                System.out.println(data);
                fw = new FileWriter(path,true);
                fw.write(Long.toString(getSeqno(data)) + " " + Long.toString(time) + "\n");
                fw.close();
            }                               
        }
        catch(SocketTimeoutException e)
        {
            writeToLog(p,"SOCKET EXCEPTION HAS BEEN CAUGHT!!!" + Long.toString(System.currentTimeMillis()));
            e.printStackTrace();
        }
        catch(IOException e)
        {
            writeToLog(p,"IO EXCEPTION HAS BEEN CAUGHT!!!" + Long.toString(System.currentTimeMillis()));
            e.printStackTrace();
        }
        clientSocket.close();
    }
    catch(SocketException e){}
    //fw.close();
}

0 个答案:

没有答案