如何在Android中通过Handler传递消息? [英] How can I pass message via Handler in Android?

查看:66
本文介绍了如何在Android中通过Handler传递消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Android中的工作处理程序.我做了Android服务器和套接字类.当有人连接到服务器时,我想从套接字向mainactivity发送一些消息(即"New Connect").我不知道如何从套接字传递到mainactivity. (更多评论)

I'm learning how work handler in Android. I did Android server and socket class. I want send some message (i.e. "New Connect") from socket to mainactivity, when somebody connect to server. I can't figure out how to pass from socket to mainactivity. (More in comments)

HttpServerActivity.java

HttpServerActivity.java

public class HttpServerActivity extends Activity implements OnClickListener{

private SocketServer s;
private static final int READ_EXTERNAL_STORAGE = 1;

Button btn1, btn2;

// There I'm trying to send message to button, when somebody connected
Handler h = new Handler(){
    @Override
    public void handleMessage(Message msg){
        super.handleMessage(msg);
        String text = (String)msg.obj;
        btn1.setText(text);
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_http_server);

    Button btn1 = (Button)findViewById(R.id.button1);
    Button btn2 = (Button)findViewById(R.id.button2);

    btn1.setOnClickListener(this);
    btn2.setOnClickListener(this);

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.http_server, menu);
    return true;
}


@Override
public void onClick(View v) {

    if (v.getId() == R.id.button1) {

        int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);

        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                    this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE);
        } else {
            // I dont know figure out in this place 
            s = new SocketServer(h);
            s.start();
        }
    }
    if (v.getId() == R.id.button2) {
        s.close();
        try {
            s.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {

        case READ_EXTERNAL_STORAGE:
            if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                // I dont know figure out in this place 
                s = new SocketServer(h);
                s.start();
            }
            break;

        default:
            break;
    }
}
}

SocketServer.java

SocketServer.java

public class SocketServer extends Thread {

private final Handler mHandler;
public SocketServer(Handler handler)
{
    mHandler = handler;
}
ServerSocket serverSocket;
public final int port = 12345;
boolean bRunning;
public void close() {
    try {
        serverSocket.close();
    } catch (IOException e) {
        Log.d("SERVER", "Error, probably interrupted in accept(), see log");
        e.printStackTrace();
    }
    bRunning = false;
}

public Handler mHandler;
public void run() {
    try {
        Log.d("SERVER", "Creating Socket");
        serverSocket = new ServerSocket(port);
        bRunning = true;
        while (bRunning) {
            Log.d("SERVER", "Socket Waiting for connection");
            Socket s = serverSocket.accept();
            Log.d("SERVER", "Socket Accepted");

            // trying to send some message
            String[] messageString = new String[1];

            Message message = Message.obtain();
            messageString[0]="OK";
            message.obj = messageString;

            mHandler.sendMessage(message);

            OutputStream o = s.getOutputStream();
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(o));

            out.write("HTTP/1.0 200 OK\n" +
                    "Date: Fri, 31 Dec 1999 23:59:59 GMT\n" +
                    "Content-Type: text/html\n" +
                    "Content-Length: 1354\n" +
                    "\n" +
                    "<html>\n" +
                    "<body>\n" +
                    "<h1> Connected </h1>\n" +
                    "</body>\n" +
                    "</html>");
            out.flush();


            while (!((tmp = in.readLine()).isEmpty()))
            {
                Log.d("Header", tmp);
                if (tmp.startsWith("GET"))
                {
                    getRequest = tmp;
                }
            }

            s.close();
            Log.d("SERVER", "Socket Closed");

        }
    }
    catch (IOException e) {
        if (serverSocket != null && serverSocket.isClosed())
            Log.d("SERVER", "Normal exit");
        else {
            Log.d("SERVER", "Error");
            e.printStackTrace();
        }
    }
    finally {
        serverSocket = null;
        bRunning = false;
    }
}

}

推荐答案

这是几年前我参与的一个更大项目的样本.您将无法按原样运行,但是我认为您可以看到Service与Activity之间的通信是如何工作的.随时询问是否不清楚

This is a sample of a bigger project I was involved a few years ago. You will not be able to run as it is, but I think you can see how the communication between a Service and an Activity works. Feel free to ask if anything is not clear

服务

public class BluetoothService {

   private final Handler mHandler;

    public BluetoothService(Context context, Handler handler) {

         mHandler = handler;
    }

    public synchronized void Connecting(...) {

      ...

      Message MenssageToActivity = mHandler.obtainMessage(Cliente_Bluetooth.MESSAGE_HELLO);
      Bundle bundle = new Bundle();
      bundle.putString(BluetoothClient.DEVICE_NAME, " Gorkatan");
      MensajeParaActivity.setData(bundle);
      mHandler.sendMessage(MensajeParaActivity);

      ...

    }
}

活动

public class BluetoothClient{

      public static final int MESSAGE_HELLO = 1;
      public static final int MESSAGE_BYE = 2;

      @Override
      protected void onCreate(Bundle savedInstanceState) {

            mBluetoothService = new BluetoothService(this, mHandler);
      }

      private final Handler mHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {


                case MESSAGE_HELLO:

                    String mName = null; 
                    mName = msg.getData().getString(DEVICE_NAME);

                    Toast.makeText(getApplicationContext(), "Hello "+ mName, Toast.LENGTH_SHORT).show();

                break; 

                case MESSAGE_BYE:

                    System.out.println("Bye!")

                break;


}

这是整个项目(带有西班牙语的注释和变量名):

Here it is the whole project (which has got comments and variable names in Spanish):

https://github .com/ignacio-alorre/PDF-Dispenser/tree/master/Client/Cliente_Bluetooth/src/com/cliente_bluetooth

这篇关于如何在Android中通过Handler传递消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆