Android一直在服务中运行代码

时间:2015-01-25 12:44:13

标签: android multithreading service client server

我想创建一个在后台运行的服务,并检查客户端是否向服务器发送消息并回复它。

这是我到目前为止所尝试的内容:

package com.server.test;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerService extends Service {

    private static ServerSocket serverSocket;
    private static Socket clientSocket;
    private static InputStreamReader inputStreamReader;
    private static BufferedReader bufferedReader;
    private static String message;

    Thread serverThread;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {

        System.out.println("hello1");

        Toast.makeText(this, "Server Started", Toast.LENGTH_LONG).show();

        serverThread = new Thread(new Runnable() {
            public void run() {
                try {
                    System.out.println("hello2");
                    try {
                        serverSocket = new ServerSocket(4444);

                    } catch (IOException e) {
                        System.out.println("Could not listen on port: 4444");
                    }

                    System.out.println("Server started. Listening to the port 4444");

                    while (true) {
                        System.out.println("hello3");
                        try {

                            clientSocket = serverSocket.accept(); 
                            inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
                            bufferedReader = new BufferedReader(inputStreamReader); 
                            message = bufferedReader.readLine();

                            System.out.println(message);
                            inputStreamReader.close();
                            clientSocket.close();

                        } catch (IOException ex) {
                            System.out.println("Problem in message reading");
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        serverThread.start();
    }
}

问题是,当代码在onCreate()中时,它只在服务创建时执行,我希望它一直运行。那么我在哪里将代码放在Service类中以便它一直运行?

最诚挚的问候, 亚历

0 个答案:

没有答案