我已经建立了一个应用程序使用Socket.io和安卓网络发现。当服务器启动,android设备解析服务时,我尝试创建一个套接字,但它从未在第一次尝试中工作。我必须杀死这个应用程序并重新启动它,然后它就可以正常工作了。服务器正在接入点上运行。连接到网络是好的,但我不能平服务器。但是正如前面提到的,如果我杀死这个应用程序并再次运行它,它就会运行得很好。
Eidt 2
经过进一步的调试,我将崩溃的范围缩小到应用程序设置wifi连接的任何时候。ssid和密码是从qrcode获得的,应用程序设置wifi连接。
读取qr码数据
@Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barCodes = detections.getDetectedItems();
if (!receivedDetection) {
if (barCodes.size() != 0) {
Log.i(TAG, "received a Barcode");
receivedDetection = true;
Gson g = new Gson();
try {
barCodeData = g.fromJson(barCodes.valueAt(0).rawValue, AccessPointCredentials.class);
} catch (Exception e) {
barCodeData = new AccessPointCredentials();
barCodeData.setSsid(barCodes.valueAt(0).rawValue);
barCodeData.setPass(null);
e.printStackTrace();
connectToWifi(barCodeData);
}
connectToWifi()
private void connectToWifi(final AccessPointCredentials credentials) {
new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object... objects) {
WifiManager wifiManager = (WifiManager) mActivity.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
int netId;
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
ie.printStackTrace();
for (WifiConfiguration tmp : wifiManager.getConfiguredNetworks()) {
if (tmp.SSID.equals("\"" + credentials.getSsid() + "\"")) {
netId = tmp.networkId;
boolean enabled = wifiManager.enableNetwork(netId, true);
Log.i(TAG, "doInBackground: Enabled? " + enabled);
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
mActivity.onBackPressed();
return null;
final String[] apSettings = {credentials.getSsid(), credentials.getPass()};
final WifiConnect WifiTask = new WifiConnect(mActivity);
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
WifiTask.execute(apSettings);
this.cancel(true);
return null;
@TargetApi(23)
@Override
protected void onPostExecute(Object aVoid) {
super.onPostExecute(aVoid);
if (Build.VERSION.RELEASE.equalsIgnoreCase("6.0")) {
if (!Settings.System.canWrite(mActivity)) {
Intent goToSettings = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
goToSettings.setData(Uri.parse("package:" + mActivity.getPackageName()));
mActivity.startActivity(goToSettings);
} else {
bindToNetwork();
} else {
bindToNetwork();
}.execute();
}
bindToNetwork()
private void bindToNetwork() {
final ConnectivityManager connectivityManager = (ConnectivityManager) mActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new NetworkRequest.Builder();
//set the transport type do WIFI
builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
connectivityManager.requestNetwork(builder.build(), new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
connectivityManager.bindProcessToNetwork(network);
} else {
//This method was deprecated in API level 23
ConnectivityManager.setProcessDefaultNetwork(network);
try {
//do a callback or something else to alert your code that it's ok to send the message through socket now
} catch (Exception e) {
e.printStackTrace();
connectivityManager.unregisterNetworkCallback(this);
}
编辑
布尔方法isServerReachable()控制异常
java.net.SocketException: socket failed: ENONET (Machine is not on the network)
public boolean isServerReachable(){
boolean isReachable;
try {
isReachable = InetAddress.getByName(mService.getHost().getHostAddress()).isReachable(5000);
} catch (Exception e) {
e.printStackTrace();
isReachable = false;
Log.i(TAG, "onServiceResolved: Server reachable? " + String.valueOf(isReachable));
Log.i(TAG, "onServiceResolved: Is Network online? " + String.valueOf(isNetworkOnline()));