我正在开发一个Android应用程序(我是新手),并且正在尝试打开套接字并在启动应用程序时检查连接状态。
为此,我有一个MainActivity可以启动并绑定到服务。在此服务的onBind()方法上,我调用一个函数openSocket()尝试打开具有给定IP地址和端口的套接字。为了建立此连接,我使用了AsyncTask,在其中尝试捕获在doInBackground()中打开套接字时的异常,并根据onPostExecute()中的连接状态更新布尔值。
在MainActivity中,我想检索此布尔值(Service.getConnectionStatus())。
问题是Service.getConnectionStatus()在onPostExecute()之前在MainActivity中被调用,导致布尔值未正确更新。
我已经进行了几天的研究,尝试了许多不同的事情,但现在我很困惑……有人能在等待MainActivity中的getConnectionStatus调用之前等待onPostExecute()完成吗?>
我尝试为AsyncTask设置侦听器,但结果是相同的。我也尝试过通过不同的方法调用openSocket(),但是没有成功...
谢谢您的帮助。
MyService.java
public class MyService extends Service {
private final IBinder mIBinder = new LocalBinder();
private Socket mSocket;
private String mDstAddress = "192.168.0.222";
private int mDstPort = 23;
private Boolean mConnectionStatus = false;
public class LocalBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
openSocket(mDstAddress, mDstPort);
return mIBinder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
public int getConnectionStatus() {
if (mConnectionStatus) {
return 1;
} else {
return 0;
}
}
public void closeSocket() {
if (mSocket != null) {
try {
mSocket.close();
} catch (IOException ex) {
//handle exception
}
}
mSocket = null;
}
public void openSocket(String dstAddress, int portAddress) {
mDstAddress = dstAddress;
mDstPort = portAddress;
ConnectSocket connect =
new ConnectSocket(mDstAddress, mDstPort);
connect.execute();
}
public class ConnectSocket extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
ConnectSocket(String addr, int port) {
dstPort = port;
dstAddress = addr;
}
@Override
protected Void doInBackground(Void... voids) {
try {
mSocket = new Socket(mDstAddress, mDstPort);
mConnectionStatus = true;
} catch (UnknownHostException e) {
mConnectionStatus = false;
response = "UnknownHostException: " + e.toString();
e.printStackTrace();
closeSocket();
} catch (IOException e) {
mConnectionStatus = false;
response = "IOException: " + e.toString();
e.printStackTrace();
closeSocket();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
if (response.contains("Exception")) {
mConnectionStatus = false;
} else {
mConnectionStatus = true;
}
this.cancel(true);
super.onPostExecute(aVoid);
}
}
MainActivity.java(仅onServiceConnected):
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i(TAG, "onServiceConnected");
MyService.LocalBinder binder = (MyService.LocalBinder) service;
mService = binder.getService();
mIsBound = true;
int statusResult = mService.getConnectionStatus();
Log.i(TAG, "statusResult: " + Integer.toString(statusResult));
mDisplayNumber.setText(Integer.toString(statusResult));
if (statusResult == 0) {
createDialog();
}
}