次のようなインテント メソッドを使用する場合、オブジェクト ストリーム (例: BufferedReader または DataOutputStream n など) を他のアクティビティ( Client_layoutActivity.class から chat_wall.class へ) に渡すにはどうすればよいですか。
Intent i = new Intent(Client_layoutActivity.this, chat_wall.class);
startActivity(i);
複数のページで構成されるチャット アプリケーションを作成しました。最初のページはログインページです。最初のページで、クライアントはソケットを使用してサーバーと通信します。ログインプロセスが成功すると、サーバーは「ログイン成功」を送信します。その後、クライアント側は 1 ページ目 (ログイン ページ) から 2 ページ目 (チャット ウォール ページ) にレイアウトを変更します。最初のページからソケット、BufferedReader、および DataOuputstream メソッドを使用することを意味します (ログイン プロセスのソケットはまだ接続されていると想定しているため、このソケットを使用して 2 番目のページ (チャット プロセス) で通信できます)。したがって、これを使用するために、オブジェクト Socket、BufferedReader、および DataOuputstream を 2 番目のページに渡したいと思います。私は以下のコードを書きます:
PAGE 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");
}
PAGE 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");
}
}
}