我有一个执行器,该执行器运行一会儿true循环,仅对服务器执行ping操作。现在,我需要使用此数据更新UI,因此我正在使用处理程序。
我的主要活动是:
private void createGeneralHandler() {
generalHandler = new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg){
switch (msg.what){
case SERVER_RESPONSE:
serverTextView.append("\n"+msg.obj);
break;
default:
super.handleMessage(msg);
}
}
};
}
这将在主要活动中创建一个名为generalHandler
的字段。
现在NetworkTask
可运行程序需要了解此处理程序,才能将消息发送到右侧?
所以我的主要活动是:
networkExecutor = Executors.newSingleThreadExecutor();
networkTask = new NetworkTask(serverIPAddress, serverPort);
networkTask.setRequest("I WANT DATA");
networkTask.setHandler(generalHandler); //IS THIS WRONG ???
networkExecutor.execute(networkTask);
networkTask
只是一个独立运行的文件,其定义如下:
public class NetworkTask implements Runnable {
private int port;
private String ipAddress;
private int pollInterval;
private Socket socket = null;
private PrintWriter out = null;
private BufferedReader br = null;
private String request = null;
private String response = null;
private static final int SERVER_RESPONSE = 1;
private Handler handler = null;
public NetworkTask(String ipAddress, int port){
this.port = port;
this.ipAddress = ipAddress;
this.pollInterval = 50;
}
@Override
public void run() {
try {
socket = new Socket(ipAddress, port);
out = new PrintWriter(socket.getOutputStream(), true);
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
try {
while (!Thread.currentThread().isInterrupted()) {
Thread.sleep(pollInterval);
out.println(request);
try {
response = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if(!response.equals("doNothing")){
Message message = new Message();
message.what = SERVER_RESPONSE;
message.obj = response;
handler.sendMessage(message);
}else if(response.equals("Nothing Connected to Server!")){
Message message = new Message();
message.what = SERVER_RESPONSE;
message.obj = response;
handler.sendMessage(message);
}
}
} catch (InterruptedException threadE) {
try {
br.close();
out.close();
socket.close();
} catch (IOException socketE) {
socketE.printStackTrace();
}
Log.i("NETWORK_TASK_THREAD", "NETWORK TASK closed gracefully!");
}
}
public void setRequest(String request) {
this.request = request;
}
public void setHandler(Handler handler) {
this.handler = handler;
}
}
答案 0 :(得分:1)
回答您的问题会有些武断。由于实施只是设计选择,因此不会有对与错,但好与不好。
以下是我要强调的要点:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="practice-area" id="practice-area">
<option value="0">Select</option>
<optgroup label="NSW">
<option value="1397">Armidale</option>
</optgroup>
<optgroup label="NT">
<option value="1402">Darwin</option>
</optgroup>
</select>
,只要您不在主线程上进行任何网络调用或繁重的处理,就可以了。networkTask.setHandler(generalHandler);
或onStop()
中适当中断了Runnable,以避免潜在的内存泄漏。onDestroy()
块中进行清理的良好实践,这可以保证在执行期间发生其他异常的情况下进行清理。一种替代方法是实现finally {..}
和ViewModel
并执行操作。这不会因不必要的处理而使您的活动肿。