Android线程服务问题

时间:2011-04-06 09:11:33

标签: android

我正在运行远程服务,我正在生成一个新线程以通过套接字继续轮询传入消息,然后在某些时间间隔我想停止套接字并稍后重新启动...停止工作正常(stopUARTConnection( ))但重新启动(startUARTConnection)不会再次导致while循环..有人能告诉我什么错了吗?

public class BackgroundService extends Service{

ServerSocket server = null;
Socket socketClient = null;
InputStream is = null;
BufferedReader br = null;
char[] buff = null;
boolean threadRunning = true;

private static final String TAG = BackgroundService.class.getSimpleName();
private Thread socketThread = null;
int temp = 0;

@Override
public IBinder onBind(Intent intent) {
    if (BackgroundService.class.getName().equals(intent.getAction())) {
        Log.d(TAG, "Bound by intent " + intent);
        return apiEndpoint;
    } else {
        return null;
    }
}

private final Object latestIncomingMessage = new Object();
private List<MessageCollectorListener> listeners = new ArrayList<MessageCollectorListener>();
private Message message = new Message(" ");

private MessageCollectorApi.Stub apiEndpoint = new MessageCollectorApi.Stub() {
    @Override
    public void removeListener(MessageCollectorListener listener) throws RemoteException {
        synchronized (listener) {
            listeners.remove(listener);
        }
    }

    @Override
    public Message getValue() throws RemoteException {
        synchronized (latestIncomingMessage) {
            return message;
        }
    }

    @Override
    public void addListener(MessageCollectorListener listener) throws RemoteException {
        synchronized (listener) {
            listeners.add(listener);
        }
    }

    @Override
    public void startBroadCastConn() throws RemoteException {
        try {
            startUARTConnection();
        } catch (IOException e) {
            Log.d("B Service", "Stop UART CONNECTION");
        }

    }

    @Override
    public void stopBroadCastConn() throws RemoteException {
        try {
            stopUARTConnection();
        } catch (IOException e) {
            Log.d("B Service", "Stop UART CONNECTION");
        }           
    }
};

public boolean createSocket(int port) {
    try{
        server = new ServerSocket(port);
    } catch (IOException e) {
        return false;
    }
    return true;
}

public boolean listenSocket(){
    try{
        socketClient = server.accept();
    } catch (IOException e) {
        return false;
    }
    return true;
}

@Override
public void onCreate() {
    super.onCreate();
    socketThread = new Thread(){
        @Override
        public void run() {
            while(threadRunning){
                boolean socketCreated = createSocket(8080);
                boolean socketListen = listenSocket();
                if(socketListen == true && socketCreated == true){
                    //To add code for processing data..
                    threadRunning = true;
                }
                try {
                    recycle();
                } catch (IOException e) {
                    //e.printStackTrace();
                }
            }
        }   
    };
    socketThread.start();
}
public void stopUARTConnection() throws IOException{
    recycle();
    threadRunning = false;
}

public void startUARTConnection() throws IOException{
    recycle();
    threadRunning = true;
}

private void recycle() throws IOException{
    if(socketClient != null){
        socketClient.close();
        socketClient = null;
    }   
    if(is != null)
        is.close();
    if(server != null){
        server.close();
        server = null;
    }
}

@Override
public void onDestroy() {
    super.onDestroy();
    try {
        recycle();
    } catch (IOException e) {
        Log.d("B Service", "Failed to recycle all values");
    }
    socketThread = null;
}

}

3 个答案:

答案 0 :(得分:2)

您只创建一次Thread。因此循环只运行一次,直到它被指示退出。

public void startUARTConnection() throws IOException{
    recycle();
    socketThread = new SocketThread();
    socketThread.start();
}

public void stopUARTConnection() throws IOException{
    recycle();
    socketThread = null;
}

private class SocketThread extends Thread {
    @Override
    public void run() {
        // Loop until socketThread is assigned something else 
        // (a new Thread instance or simply null)
        while (socketThread==this){
            boolean socketCreated = createSocket(8080);
            boolean socketListen = listenSocket();
            if(socketListen == true && socketCreated == true){
                // To add code for processing data..
            }
            try {
                recycle();
            } catch (IOException e) {
                //e.printStackTrace();
            }
        }
    }   
};

答案 1 :(得分:0)

当您调用stopUARTConnection时,您正在设置threadRunning = false ...此时,您的while循环正在退出...在startUARTConnection中,您将threadRunning设置为true,但您没有重新启动该线程。

正如@Marvin指出的那样,you can't just call start on the thread object,你需要重新创建它。

答案 2 :(得分:0)

我认为最好使用TimerTask代替thread / while和ConditionVariable代替布尔变量threadRunning