将android套接字活动转换为片段
我目前正在尝试将android套接字活动转换为android套接字片段。然而,在将所有代码导出到fragment方法之后,当按下connect按钮时,应用程序总是停止工作。以下是mainActivity的代码将android套接字活动转换为片段,android,sockets,fragment,Android,Sockets,Fragment,我目前正在尝试将android套接字活动转换为android套接字片段。然而,在将所有代码导出到fragment方法之后,当按下connect按钮时,应用程序总是停止工作。以下是mainActivity的代码 public class MainActivity extends Activity { private static TextView textResponse; private EditText editTextAddress, editTextPort; p
public class MainActivity extends Activity {
private static TextView textResponse;
private EditText editTextAddress, editTextPort;
private Button buttonConnect;
private String message = "Hi client!";
private static String kq = "";
private ClientTask myClientTask;
private OnListener listener;
private static boolean flag = true;
Socket socket = null;
public interface OnListener {
void listener(String text);
}
public void addListener(OnListener listener) {
this.listener = listener;
}
static Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (flag) {
kq += msg.obj.toString() + "\r\n";
textResponse.setText(kq);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextAddress = (EditText) findViewById(R.id.address);
editTextPort = (EditText) findViewById(R.id.port);
buttonConnect = (Button) findViewById(R.id.connect);
textResponse = (TextView) findViewById(R.id.response);
buttonConnect.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
myClientTask = new ClientTask(editTextAddress.getText()
.toString(), Integer.parseInt(editTextPort.getText()
.toString()));
myClientTask.execute();
}
});
}
public class ClientTask extends AsyncTask<String, String, String> implements
OnListener {
String dstAddress;
int dstPort;
PrintWriter out1;
ClientTask(String addr, int port) {
dstAddress = addr;
dstPort = port;
}
@Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
socket = new Socket(dstAddress, dstPort);
out1 = new PrintWriter(socket.getOutputStream(), true);
//out1.print("Hello server!");
out1.flush();
BufferedReader in1 = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
do {
try {
if (!in1.ready()) {
if (message != null) {
MainActivity.handler.obtainMessage(0, 0, -1,
"Server: " + message).sendToTarget();
message = "";
}
}
int num = in1.read();
message += Character.toString((char) num);
} catch (Exception classNot) {
}
} while (!message.equals("bye"));
try {
sendMessage("bye");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
try {
if (socket.isClosed()) {
flag = false;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Lỗi nhập!", Toast.LENGTH_LONG).show();
}
super.onPostExecute(result);
}
@Override
public void listener(String text) {
// TODO Auto-generated method stub
sendMessage(text);
}
void sendMessage(String msg) {
try {
out1.print(msg);
out1.flush();
if (!msg.equals("bye"))
MainActivity.handler.obtainMessage(0, 0, -1, "Me: " + msg)
.sendToTarget();
else
MainActivity.handler.obtainMessage(0, 0, -1,
"Ngắt kết nối!").sendToTarget();
} catch (Exception ioException) {
ioException.printStackTrace();
}
}
}
public void send(View v) {
addListener(myClientTask);
if (listener != null)
listener.listener(((EditText) findViewById(R.id.editText1))
.getText().toString());
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
try {
if (listener != null)
listener.listener("bye");
socket.close();
} catch (Exception e) {
// TODO: handle exception
}
super.onDestroy();
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
try {
if (listener != null)
listener.listener("bye");
socket.close();
} catch (Exception e) {
// TODO: handle exception
}
super.onStop();
}
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
}
公共类MainActivity扩展活动{
私有静态文本视图文本响应;
专用编辑地址,编辑端口;
私人按钮连接;
私有字符串消息=“Hi client!”;
私有静态字符串kq=“”;
私有客户端任务myClientTask;
私人监听者;
私有静态布尔标志=true;
套接字=空;
公共接口在线监听器{
无效侦听器(字符串文本);
}
public void addListener(OnListener侦听器){
this.listener=listener;
}
静态处理程序=新处理程序(){
@凌驾
公共无效handleMessage(消息消息消息){
国际单项体育联合会(旗){
kq+=msg.obj.toString()+“\r\n”;
textResponse.setText(kq);
}
}
};
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextAddress=(EditText)findViewById(R.id.address);
editTextPort=(EditText)findViewById(R.id.port);
buttonConnect=(按钮)findViewById(R.id.connect);
textResponse=(TextView)findViewById(R.id.response);
buttonConnect.setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
myClientTask=新的ClientTask(editTextAddress.getText()
.toString(),Integer.parseInt(editTextPort.getText())
.toString());
myClientTask.execute();
}
});
}
公共类ClientTask扩展了AsyncTask实现
在线监听器{
字符串地址;
国际数据传输端口;
打印输出1;
ClientTask(字符串地址,int端口){
dstAddress=addr;
dstPort=端口;
}
@凌驾
受保护的void onProgressUpdate(字符串…值){
//TODO自动生成的方法存根
super.onProgressUpdate(值);
}
@凌驾
受保护的字符串doInBackground(字符串…参数){
//TODO自动生成的方法存根
试一试{
套接字=新的套接字(dstAddress,dstPort);
out1=新的PrintWriter(socket.getOutputStream(),true);
//out1.打印(“你好服务器!”);
out1.flush();
BufferedReader in1=新的BufferedReader(新的InputStreamReader(
getInputStream());
做{
试一试{
如果(!in1.ready()){
如果(消息!=null){
MainActivity.handler.ActainMessage(0,0,-1,
服务器:“+消息).发送目标();
message=“”;
}
}
int num=in1.read();
message+=Character.toString((char)num);
}catch(异常类not){
}
}而(!message.equals(“再见”);
试一试{
发送信息(“再见”);
}捕获(例外e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}最后{
socket.close();
}
}捕获(IOE异常){
e、 printStackTrace();
}
返回null;
}
@凌驾
受保护的void onPostExecute(字符串结果){
试一试{
if(socket.isClosed()){
flag=false;
}
}捕获(例外e){
Toast.makeText(getApplicationContext(),“Lỗi nhập!”,Toast.LENGTH_LONG).show();
}
super.onPostExecute(结果);
}
@凌驾
公共void侦听器(字符串文本){
//TODO自动生成的方法存根
发送消息(文本);
}
无效发送消息(字符串消息){
试一试{
输出1.打印(msg);
out1.flush();
如果(!msg.equals(“bye”))
MainActivity.handler.ActainMessage(0,0,-1,“Me:+msg)
.sendToTarget();
其他的
MainActivity.handler.ActainMessage(0,0,-1,
“Ngắt kết nối!”).sendToTarget();
}捕获(异常ioException){
ioException.printStackTrace();
}
}
}
公共无效发送(视图五){
addListener(myClientTask);
if(侦听器!=null)
listener.listener(((EditText)findViewById(R.id.editText1))
.getText().toString());
}
@凌驾
受保护的空onDestroy(){
//TODO自动生成的方法存根
试一试{
if(侦听器!=null)
倾听者。倾听者(“再见”);
socket.close();
}捕获(例外e){
//TODO:处理异常
}
super.ondestory();
}
@凌驾
受保护的void onStop(){
//TODO自动生成的方法存根
试一试{
if(侦听器!=null)
倾听者。倾听者(“再见”);
socket.close();
}捕获(例外e){
//TODO:处理异常
}
super.onStop();
}
公共void onClick(视图v){
Intent Intent=新的Intent(getApplicationContext(),MainActivity.class);
public class blank extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private static TextView textResponse;
private static EditText editTextAddress, editTextPort;
private static Button buttonConnect;
private String message = "Hi Nice to meet you Client";
private static String kq= "";
private static boolean flag=true;
private OnListener listener;
private ClientTask myClientTask;
Socket socket = null;
public interface OnListener {
void listener(String text);
}
public void addListener(OnListener listener) {
this.listener = listener;
}
static Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (flag) {
kq += msg.obj.toString() + "\r\n";
textResponse.setText(kq);
}
}
};
private OnFragmentInteractionListener mListener;
public blank() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static blank newInstance(String param1, String param2) {
blank fragment = new blank();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = (View) inflater.inflate(R.layout.fragment_blank, container, false);
editTextAddress = (EditText)view.findViewById(R.id.address);
editTextPort = (EditText)view.findViewById(R.id.port);
buttonConnect = (Button)view.findViewById(R.id.connect);
textResponse = (TextView)view.findViewById(R.id.response);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
buttonConnect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myClientTask = new ClientTask(editTextAddress.getText()
.toString(), Integer.parseInt(editTextAddress.getText()
.toString()));
myClientTask.execute();
}
});
super.onActivityCreated(savedInstanceState);
}
public class ClientTask extends AsyncTask<String, String, String> implements
OnListener {
String dstAddress;
int dstPort;
PrintWriter out1;
ClientTask(String addr, int port) {
dstAddress = addr;
dstPort = port;
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
@Override
protected String doInBackground(String... params) {
try {
socket = new Socket(dstAddress, dstPort);
out1 = new PrintWriter(socket.getOutputStream(), true);
out1.flush();
BufferedReader in1 = new BufferedReader(new InputStreamReader(
socket.getInputStream()
));
do {
try {
if (!in1.ready()) {
if (message != null) {
blank.handler.obtainMessage(0, 0, -1,
"Server : " + message).sendToTarget();
message = "";
}
}
int num = in1.read();
message += Character.toString((char)num);
}
catch (Exception classNot) {
}
} while ((message.equals("bye !")));
try {
sendMessage("bye");
}catch (Exception e) {
e.printStackTrace();
} finally {
socket.close();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
try {
if (socket.isClosed()) {
flag = false;
}
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(), "Disconnect!", Toast.LENGTH_LONG).show();
}
super.onPostExecute(result);
}
@Override
public void listener(String text) {
sendMessage(text);
}
void sendMessage(String msg) {
try {
out1.print(msg);
out1.flush();
if (!msg.equals("bye"))
blank.handler.obtainMessage(0, 0, -1, "Me: " + msg)
.sendToTarget();
else
blank.handler.obtainMessage(0, 0, -1,
"Disconnected !").sendToTarget();
} catch (Exception ioException) {
ioException.printStackTrace();
}
}
}
public void send(View v) {
addListener(myClientTask);
if (listener != null)
{
listener.listener(((EditText)getView().findViewById(R.id.editText1))
.getText().toString());
}
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
try {
if (listener != null)
listener.listener("bye");
socket.close();
} catch (Exception e) {
// TODO: handle exception
}
super.onDestroy();
}
@Override
public void onStop() {
// TODO Auto-generated method stub
try {
if (listener != null)
listener.listener("bye");
socket.close();
} catch (Exception e) {
// TODO: handle exception
}
super.onStop();
}
public void onClick(View v) {
Intent intent = new Intent(getActivity().getApplicationContext(), blank.class);
startActivity(intent);
getActivity().finish();
}
}