1

我的服务从 DSL 路由器“FRITZ!Box”接收电话信息。当有人打电话时,路由器会在端口 1012 将电话号码发送到我的服务。它可以工作,但过了一段时间我的服务不再接收。该服务正在运行,这不是原因,但它没有从我的路由器中读取任何内容。没有抛出异常,服务保持在while循环中......

public class CallMonitorService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

    Notification notification = new Notification(icon, "service", System.currentTimeMillis());
        Intent notificationIntent = new Intent(this, Main.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notification.setLatestEventInfo(this, "title", "text", pendingIntent);
        notification.flags |= Notification.FLAG_NO_CLEAR;
        startForeground(1337, notification);

        new ListenThread().start();
    }
}

class ListenThread extends Thread {

    public void run() {

        Looper.prepare();

        Handler handler = new Handler() {

            public void handleMessage(Message msg) {

                BufferedReader in = null;

                Socket socket = new Socket();
                socket.setKeepAlive(true);
                socket.connect(new InetSocketAddress(InetAddress.getByName("http://fritz.box"), 1012), 30*1000);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()), 8 * 1024);

                String line = null;

                while ((line = in.readLine()) != null) {
                    Log.d("TAG", line);
                }


            }
        };


        handler.sendEmptyMessage(0);
        Looper.loop();
    }


}
4

1 回答 1

0

所以看起来一旦你的路由器停止发送数据,循环就会结束并且你的处理程序退出handleMessage。此时,您需要向处理程序发送另一条消息,以使其连接并再次开始读取数据。

此外,这个问题看起来可能很相似,并且在使用 readline 通过套接字读取数据时处理问题。挂在 inStream.readline() 上的 Android TCP 应用程序

希望有帮助。

于 2013-07-24T00:54:08.660 回答