Я пытаюсь реализовать интерфейс REST в android, и мне нужен поток в фоновом режиме, отправляющий сообщения «Я жив» на ip-адрес. Для этого я создал вызванный поток RestPostThread, который работает в фоновом режиме, пока я делаю что-то в своем потоке пользовательского интерфейса.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;
}
Так что конкретно вопрос? –
Извините, я написал can и я имел в виду, что не могу: «Я не могу выйти из петлителя или отправить ему другое сообщение с другим IP-адресом или что-то в этом роде». – Hart
Извините, если его отключить, но очень легко узнать, как использовать библиотеку, например «Дооснащение», http://square.github.io/retrofit, чем работать с сетью с помощью фоновых задач. – Shailesh