如果我使用这样的意图方法,如何将对象流(例如:BufferedReader 或 DataOutputStream n 等)传递给其他活动(从 Client_layoutActivity.class 到 chat_wall.class ):
Intent i = new Intent(Client_layoutActivity.this, chat_wall.class);
startActivity(i);
我制作了一个包含多个页面的聊天应用程序。第一个页面是登录页面。在第一页中,客户端使用套接字与服务器进行通信。登录过程成功后,服务器将发送“登录成功”。之后,客户端将布局从第一页(登录页面)更改为第二页(聊天墙页面)。我的意思是从第一页使用套接字、BufferedReader 和 DataOuputstream 方法(我假设登录过程的套接字仍然连接,所以我仍然可以使用这个套接字在第二页进行通信 - 聊天过程)。所以我想将对象 Socket、BufferedReader 和 DataOuputstream 传递到第二页以使用它。我在下面写我的代码:
第 1 页:用于登录目的
public void login(){
try {
String name = usrname.getText().toString(); // usrname is android object edit
text
String pass = password.getText().toString();// password is android
object edit text
String sending = "login."+name + "." + pass + "." +"\n";
System.out.println("Sending Message: "+sending);
Socket clientsock = new Socket("192.168.136.6", 28000);
System.out.println("connect to the server...");
BufferedReader in = new BufferedReader(new
InputStreamReader(clientsock.getInputStream()));
DataOutputStream out = new DataOutputStream(clientsock.getOutputStream());
out.writeBytes(sending);
String line = in.readLine();
if (line.contentEquals("login success")){
Toast.makeText(this, "login success", Toast.LENGTH_SHORT).show();
Toast.makeText(this, "receive data from
server:"+clientsock.getInetAddress(), Toast.LENGTH_SHORT).show();
Intent i = new Intent(Client_layoutActivity.this, chat_wall.class);
startActivity(i);
} else {
Toast.makeText(this, "Error ", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
System.out.println(e);
System.out.println("Connection Failed");
}
第 2 页:用于聊天目的
package com.willis.layout;
import java.io.*;
import java.net.*;
import android.widget.*;
import android.os.Bundle;
import android.view.*;
import android.view.View.OnClickListener;
import android.app.Activity;
import android.R.integer;
public class chat_wall extends Activity {
Client_layoutActivity ob;
public EditText chatroom;
public Button sendbtn;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.chatwall);
sendbtn = (Button)findViewById(R.id.sendmsg);
sendbtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
sendingmsg();
}
});
chatroom = (EditText)findViewById(R.id.chatroom);
}
public void sendingmsg (){
try
{
BufferedReader in = new BufferedReader(new
InputStreamReader(clientsock.getInputStream()));
DataOutputStream out = new DataOutputStream(clientsock.getOutputStream());
String name = chatroom.getText().toString();
String send = "chat."+name+". \n";
System.out.println("Sending message: "+send);
out.writeBytes(send);
String msgin = in.readLine();
Toast.makeText(this, msgin, Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
System.out.println(e);
System.out.println("Connection Failed");
}
}
}