Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/197.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在Android中通过处理程序传递消息?_Java_Android_Sockets_Handler - Fatal编程技术网

Java 如何在Android中通过处理程序传递消息?

Java 如何在Android中通过处理程序传递消息?,java,android,sockets,handler,Java,Android,Sockets,Handler,我正在学习如何在Android中工作。我做了Android服务器和套接字类。当有人连接到服务器时,我想从套接字向mainactivity发送一些消息(即“新建连接”)。我不知道如何从套接字传递到mainactivity。(更多评论) HttpServerActivity.java public class HttpServerActivity extends Activity implements OnClickListener{ private SocketServer s; private

我正在学习如何在Android中工作。我做了Android服务器和套接字类。当有人连接到服务器时,我想从套接字向mainactivity发送一些消息(即“新建连接”)。我不知道如何从套接字传递到mainactivity。(更多评论)

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

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

}
公共类SocketServer扩展线程{
私人最终处理人;
公共SocketServer(处理程序)
{
mHandler=handler;
}
服务器套接字服务器套接字;
公共最终int端口=12345;
布尔布伦宁;
公众假期结束(){
试一试{
serverSocket.close();
}捕获(IOE异常){
d(“服务器”,“错误,可能在accept()中中断,请参阅日志”);
e、 printStackTrace();
}
布鲁宁=假;
}
公共管理者;
公开募捐{
试一试{
Log.d(“服务器”,“创建套接字”);
serverSocket=新的serverSocket(端口);
布伦宁=真;
当(布伦宁){
Log.d(“服务器”、“等待连接的套接字”);
sockets=serverSocket.accept();
Log.d(“服务器”、“接受套接字”);
//正在尝试发送一些消息
String[]messageString=新字符串[1];
Message=Message.get();
messageString[0]=“确定”;
message.obj=messageString;
mHandler.sendMessage(消息);
OutputStream o=s.getOutputStream();
BufferedWriter out=新的BufferedWriter(新的OutputStreamWriter(o));
out.write(“HTTP/1.0 200正常\n”+
日期:1999年12月31日星期五23:59:59 GMT\n+
“内容类型:text/html\n”+
“内容长度:1354\n”+
“\n”+
“\n”+
“\n”+
“已连接\n”+
“\n”+
"");
out.flush();
而(!((tmp=in.readLine()).isEmpty())
{
Log.d(“标题”,tmp);
如果(tmp.startsWith(“GET”))
{
getRequest=tmp;
}
}
s、 close();
Log.d(“服务器”,“套接字关闭”);
}
}
捕获(IOE异常){
if(serverSocket!=null&&serverSocket.isClosed()
Log.d(“服务器”,“正常退出”);
否则{
Log.d(“服务器”、“错误”);
e、 printStackTrace();
}
}
最后{
serverSocket=null;
布鲁宁=假;
}
}
}

如果计划将数据从线程发送到处理程序,则使用AcquinMessage创建消息对象

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


在这里,您可以找到一个很好的资源来解释如何使用处理程序:


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

服务

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;


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


好的,我知道如何获取消息并发送消息。。。但我仍然不知道如何在我的项目中将消息从一个类传递到另一个类