我想在android中實現一個REST接口,我需要一個線程在後臺發送「我活着」消息到一個IP地址。要做到這一點,我創建了一個線程調用RestPostThread在後臺運行,而我在我的UI線程中做東西。Android處理程序只發送一條消息
問題是,在發送第一條消息到RestPostThread後,我不能退出活套或用另一個IP或其他東西發送不同的消息給它。
下面是用戶界面和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;
}
那麼究竟是什麼問題? –
對不起,我寫了可以,我的意思是不能在「我不能退出活套或用另一個IP或其他東西發送不同的消息。」 – Hart
對不起,如果它的題外話,但它很容易學習如何使用像Retrofit,http://square.github.io/retrofit庫比處理網絡與後臺任務。 – Shailesh