我目前正在尝试将android套接字活动转换为android套接字片段。但是,将所有代码导出到片段方法后,应用程序总是在按下连接按钮时停止工作。以下是mainActivity的代码
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();
}
}
这是片段
中android socket的代码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();
}
}
代码在活动中运行良好,但在片段中运行良好。仅供参考,一旦套接字建立片段,文本视图将被更新并显示欢迎文本。我是否应该知道在哪里放置代码而不是onCreateView方法?