继承Activity的类,获取不到另一个继承Activity的类的成员(Socket)
项目需要Socket通信,手机做为客户端,这边写了一个TcpClient类。
在Activity1中实例化了TcpClient类,获取到了socket。
我要如何才能在Activity2中获得这个socket或者TcpClient实例 (需要用到TcpClient类中定义收发函数)?
Activity2
获取不到是为什么呢?是不是继承Acitivity的类里面的成员变量是在main函数里的?
Activity1
...
public static TcpClient tcpClient = null;
....
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
context = this;
bindReceiver();
connectText = findViewById(R.id.content_text);
button = findViewById(R.id.start_btn);
button.setEnabled(false);
CustomDialog.Builder builder = new CustomDialog.Builder(Welcome.this);
builder.setMessage("请使用蓝牙或WiFi进行连接");
builder.setPositiveButton(getDrawable(R.drawable.wifi_btn), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
imageViewPositive = customDialog.findViewById(R.id.positiveTextView);
//设置你的操作事项
try {
try{
checkTimeOut();
tcpClient = new TcpClient(Constants.SERVER_IP,Constants.SERVER_PORT);
exec.execute(tcpClient);
TcpClient类
public class TcpClient implements Runnable {
final private String TAG = "TcpClient";
private String serverIP = "192.168.10.2";
private int serverPort = 8080;
private Socket socket = null;
private PrintWriter pw;
private InputStream is;
private DataInputStream dis;
private Boolean isRun = true;
byte buff[] = new byte[4096];
byte content[] = new byte[160];
private String rcvMsg;
private int rcvLen;
private String rcvMsgg;
private DataOutputStream dop;
public TcpClient(String serverIP, int serverPort) {
this.serverIP = serverIP;
this.serverPort = serverPort;
}
public void closeSelf(){
isRun = false;
}
public void send(String msg){
pw.println(msg);
pw.flush();
}
@Override
public void run() {
try {
socket = new Socket(serverIP, serverPort);
socket.setSoTimeout(5000);
dop = new DataOutputStream(socket.getOutputStream());
pw = new PrintWriter(socket.getOutputStream(),true);
is = socket.getInputStream();
dis = new DataInputStream(is);
} catch (IOException e) {
e.printStackTrace();
}
while (isRun){
try {
rcvLen = dis.read(buff);
if (rcvLen!=-1){
rcvMsg = new String(buff,0,rcvLen,"utf-8");
rcvMsgg = new SocketHelper().byte2hex(buff,rcvLen);
Log.i(TAG,"run收到消息: "+ new SocketHelper().byte2hex(buff,rcvLen));
...
做成单例,来管理这个client。
在有需要地方获取client做事情。
我看不懂你表达什么意思。你说activity ,main方法???
安卓里哪有Main方法?又不需要你自己去创建应用。你注册好了,系统会帮你启动的。你好好学习基础吧。基础不好就是害人害己,浪费自己的时间,也浪费别人的时间。