如何在Android中通过Handler传递消息?

时间:2017-02-26 11:37:33

标签: java android sockets handler

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

HttpServerActivity.java

<jboss-deployment-structure>
    <deployment>
        <exclude-subsystems>
            <subsystem name="logging" />
        </exclude-subsystems>
</deployment>
</jboss-deployment-structure>

SocketServer.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;
    }
}
}

2 个答案:

答案 0 :(得分:1)

这是几年前我参与的一个更大项目的样本。您将无法按原样运行,但我认为您可以看到服务和活动之间的通信是如何工作的。随意询问是否有任何不清楚

服务

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;


}

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

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

答案 1 :(得分:0)

如果您打算将数据从线程发送到处理程序,请使用obtainMessage创建消息对象。

您还必须使用相同的处理程序实例来处理handleMessage和sendMessage。

在这里,您将找到一个很好的资源,解释如何使用Handler:

https://www.youtube.com/watch?v=LJ_pUlWzGsc