Lesson 81. Handler. We send a simple message

Lesson 81. Handler. We send a simple message


In this lesson:

– we send the simplest message to Handler

I hope you learned from the previous lesson and realized what a useful Handler thing is. We sent him a message there. Today we will do it again, but without a heap of extra code, freezing screens and program errors. A clean example to pin.

As we remember, Handler allows put in the queue, the message itself knows how process. The trick here is that he can put the message out one stream, and read from the other.

The message may contain attributes. In this article, let’s look at the simplest option, an attribute what.

Let’s write a simple client application. It, as if, will connect to the server, do some work and disconnect. On the screen we will see how the connection status changes and how ProgressBar rotates when connected.

When the connection status changes, we will send a message to Handler. And in the attribute what we put the current status. Handler reads the message from him and takes any action.

Let’s create a project:

Project name: P0811_ HandlerSimpleMessage
Build Target: Android 2.3.3
Application name: HandlerSimpleMessage
Package name: ru.startandroid.develop.p0811handlersimplemessage
Create Activity: MainActivity

strings.xml:



	HandlerSimpleMessage
	Connect

main.xml:



	
	
	
	
	

Button to start the connection, TextView to display the status of the connection and ProgressBar that works during the connection.

MainActivity.java:

package ru.startandroid.develop.p0811handlersimplemessage;

import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity {

  final String LOG_TAG = "myLogs";

  final int STATUS_NONE = 0; // нет подключения
  final int STATUS_CONNECTING = 1; // подключаемся
  final int STATUS_CONNECTED = 2; // подключено

  Handler h;

  TextView tvStatus;
  ProgressBar pbConnect;
  Button btnConnect;

  /** Called when the activity is first created. */
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    tvStatus = (TextView) findViewById(R.id.tvStatus);
    pbConnect = (ProgressBar) findViewById(R.id.pbConnect);
    btnConnect = (Button) findViewById(R.id.btnConnect);

    h = new Handler() {
      public void handleMessage(android.os.Message msg) {
        switch (msg.what) {
        case STATUS_NONE:
          btnConnect.setEnabled(true);
          tvStatus.setText("Not connected");
          break;
        case STATUS_CONNECTING:
          btnConnect.setEnabled(false);
          pbConnect.setVisibility(View.VISIBLE);
          tvStatus.setText("Connecting");
          break;
        case STATUS_CONNECTED:
          pbConnect.setVisibility(View.GONE);
          tvStatus.setText("Connected");
          break;
        }
      };
    };
    h.sendEmptyMessage(STATUS_NONE);
  }

  public void onclick(View v) {
    Thread t = new Thread(new Runnable() {
      public void run() {
        try {
          // устанавливаем подключение
          h.sendEmptyMessage(STATUS_CONNECTING);
          TimeUnit.SECONDS.sleep(2);

          // установлено
          h.sendEmptyMessage(STATUS_CONNECTED);

          // выполняется какая-то работа
          TimeUnit.SECONDS.sleep(3);

          // разрываем подключение
          h.sendEmptyMessage(STATUS_NONE);

        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    });
    t.start();
  }

}

STATUS_NONE, STATUS_CONNECTING, STATUS_CONNECTED are status constants. We will pass them in the message, in the what attribute. Of course, the names and values ​​of these constants are arbitrary and taken from the head. You can come up with and use your own.

IN onCreate we create a Handler and implement its handleMessage method. This method is responsible for handling messages intended for this Handler. According to the method input there is a message – Message. We read the what attribute and depending on the connection status change the screen:

STATUS_NONE – No connection. The Connection Button is active, TextView displays the connection status.

STATUS_CONNECTING – in progress. Connection button is inactive, we show ProgressBar, TextView displays the status of the connection.

STATUS_CONNECTED – Connected. Hiding ProgressBar, TextView displays connection status.

OnCreate, after creating Handler, we immediately send him a message with the status STATUS_NONE. To do this, we use the sendEmptyMessage method. This method creates a message, fills it with the what attribute (the value we pass to sendEmptyMessage), sets Handler as the recipient, and sends the message to the queue.

In the method onclick we create and launch a new stream. In it we, with the help sleepEmulating the process of connecting to the server, performing work and shutting down. And, as we take action, we send status messages to Handler. That is, after pressing a button Connect the status changes to STATUS_CONNECTING, the connection takes two seconds, the status changes to STATUS_CONNECTED, the action takes 3 seconds and the status changes to STATUS_NONE. Let’s check it out.

We will save everything and launch the application.

press Connect.

Connection went. ProgressBar appears, text changes and the Connect button inactive.

It takes two seconds.

Connected. ProgressBar disappears and the text changes.

It takes another 3 seconds.

Connection terminated. The Connect button is active again and the text indicates that we are not connected.

That is, to simply update the status from a new thread, we lacked the what attribute. But in addition to what the message may have a few more attributes. Consider them in the next lesson.

In the next lesson:

– create more meaningful messages for Handler




Discuss in the forum [11 replies]

Leave a Comment