我正在尝试在android中实现REST接口,我需要在后台发送一个线程,将“我还活着”的消息发送到ip地址。为此,我创建了一个线程调用的RestPostThread,它在后台运行,而我在UI线程中执行操作。
问题是,在将第一条消息发送到RestPostThread之后,我无法退出looper或使用其他IP或其他内容向其发送不同的消息。
以下是UI和RestPostThread的代码:
public class MainActivity extends AppCompatActivity{
Handler workerThreadHandler;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
final TextView text1 = (TextView) findViewById(R.id.text1);
final TextView text2 = (TextView) findViewById(R.id.text2);
setSupportActionBar(toolbar);
final RestPostThread RPT = new RestPostThread();
RPT.start();
while(workerThreadHandler == null ) {
workerThreadHandler = RPT.getThreadHandler();
}
Button buttonStop = (Button) findViewById(R.id.buttonStop);
buttonStop.setOnClickListener(new View.OnClickListener(){
public void onClick(View view) {
try {
workerThreadHandler.getLooper().quit();
}catch(Exception e){
text1.setText(e.getMessage());
text2.setText( "Exception!");
}
}
});
Button buttonSend = (Button) findViewById(R.id.buttonSend);
buttonSend.setOnClickListener(new View.OnClickListener(){
public void onClick(View view) {
try {
text1.setText(new RestGet().execute(editText.getText().toString()).get());
text2.setText("everything went well!");
}catch(Exception e){
text1.setText(e.getMessage());
text2.setText( "Exception!");
}
}
});
}
这是RestPostThread的代码:
public class RestPostThread extends Thread {
public Handler mHandler;
@Override
public void run(){
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
Log.d("MYASDASDPOASODAPO", "dentro mensaje");
while (!msg.obj.equals(null)) {
try {
Thread.sleep(1000);
URL url = new URL(msg.obj.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
String input = "<Instruction><type>put_me_in</type><room>Room 1</room></Instruction>";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
// throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
String aux = new String();
while ((output = br.readLine()) != null) {
aux = aux + output;
}
conn.disconnect();
//return aux;
} catch(MalformedURLException e) {
e.printStackTrace();
//return null;
} catch(IOException e) {
e.printStackTrace();
//return null;
} catch(Exception e) {
}
}
Log.d("CLOSING MESSAGE", "Closing thread");
}
};
Looper.loop();
}
public Handler getThreadHandler() {
return this.mHandler;
}
答案 0 :(得分:0)
看看HandlerThread
处理一个线程来处理消息。你的Handler
不应该像这样的消息循环,它将无法正常工作。这是Looper
的工作,处理发送到Message
的新Runnable
或Handler
个对象,这些对象绑定到Looper
。
无论如何,您应该仔细查看使用Loader
来处理REST类型API;或者,探索第三方库,例如改造,以处理REST。
答案 1 :(得分:0)
我设法解决了这个问题。问题是我把所有东西都包裹在里面:
while (!msg.obj.equals(null)) {}
我在这个线程和UI线程中实现了处理程序,现在我在两者之间来回通信,我的RestPostThread现在看起来像这样:
public class RestPostThread extends Thread {
public Handler mHandler,uiHandler;
public RestPostThread(Handler handler) {
uiHandler = handler;
}
@Override
public void run(){
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
try {
//Thread.sleep(1000);
URL url = new URL(msg.obj.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
String input = "<Instruction><type>put_me_in</type><room>Room 1</room></Instruction>";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
// throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
String aux = new String();
while ((output = br.readLine()) != null) {
aux = aux + output;
}
conn.disconnect();
Message msg2 = uiHandler.obtainMessage();
msg2.obj = aux;
uiHandler.sendMessage(msg2);
}catch(MalformedURLException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}catch(Exception e){
}
}
};
Looper.loop();
}
public Handler getThreadHandler() {
return this.mHandler;
}
}
在我的MainActivity中,我有这个处理程序,允许我循环#34; (基本上只是在RestPostThread和UIThread之间来回)我的Post消息,直到我决定停止改变布尔循环的MainActivity:
public Handler uiHandler = new Handler() {
public void handleMessage(Message inputMessage) {
Log.d("FROM UI THREAD",inputMessage.obj.toString());
if(loop) {
Message msg = workerThreadHandler.obtainMessage();
String url = "http://192.168.1.224:9000/xml/android_reply";
msg.obj = url;
workerThreadHandler.sendMessageDelayed(msg,1000);
}
}
};