2013-01-01 66 views
0

我是Android和Java的新手,在较小的程度上,所以如果这个问题是荒谬的原谅我。 **我也很抱歉,如果这篇文章是可怕的格式化请理解我在这里是新的,是的说明无处不在,但我不知道如何添加后续帖子,所以我只是编辑原始帖子,并添加了我收到的新信息。检查连接到服务器

我在Android项目中有一个活动,必须检查它是否可以连接到服务器。我只需点击一下按钮即可运行代码来检查服务器连接。

当我点击按钮的应用程序关闭(Unfortunately .... has stopped).

如果需要,我可以提供完整的错误日志。这里是我的代码有:

注:R.id.check_text是指一个TextView在布局XML

我需要这个文本以更改给isConnectedToServer方法的结果。

public class StartActivity extends Activity { 

public static final int timeout = 3000; 
public static final String TAG = "StartActivity"; 
public static final String url = "http://serverIP:port"; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_start); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.activity_start, menu); 
    return true; 
} 

public boolean isConnectedToServer(String url, int timeout) { 
    try { 
     URL serverURL = new URL(url); 
     URLConnection urlconn = serverURL.openConnection(); 
     urlconn.setConnectTimeout(timeout); 
     urlconn.connect(); 
     return true; 
    } catch (IOException e) { 
     Log.e(TAG, e.getLocalizedMessage(), e); 
    } catch (IllegalStateException e) { 
     Log.e(TAG, e.getLocalizedMessage(), e); 
    } 
    return false; 

} 
public void connectionReturn(View view) { 
    boolean a; 
    a = this.isConnectedToServer(url, timeout); 
    if (a == true) { 
     EditText edConnStatus = (EditText) findViewById(R.id.check_text); 
     edConnStatus.setText("Connection established"); 

    } else { 
     EditText edConnStatus = (EditText) findViewById(R.id.check_text); 
     edConnStatus.setText("Connection to server could not be established"); 
    } 

} 
} 

当然,在我的布局XML和我有一个按钮,上面写着这样的:

<Button 
    android:id="@+id/bn_checkconnection" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:onClick="connectionReturn" 
    android:text="@string/checkservconn" /> 

我明白,可给予任何帮助,谢谢大家。

近期编辑: 我改变了connectionReturn方法有参数的查看视图(即connectionReturn(查看VW)),并看到了一个的onClick失误,现在它调用connectionReturn方法。我没有得到同样的错误,我现在得到新的!当我点击按钮的应用程序冻结和Eclipse开辟了Socket.class并说:

源未发现 的JAR文件c:\ androidsdk \平台\ android17 \的android.jar没有源代码连接 附加下面的源....

AND

Eclipse中的调试窗口视图与此弹出:

螺纹[< 1>主](暂停(例外NetworkOnMainThreadException))

Socket.connect(SocketAddress,int)行:849 < - 它立即指向这一点。
的HttpConnection(HttpConnection的$地址,INT)线:76 的HttpConnection(HttpConnection的$地址,整型,HttpConnection的$ 1)行:50
的HttpConnection $ Address.connect(int)的线:340
HttpConnectionPool.get(的HttpConnection $地址,INT)线:87
HttpConnection.connect(URI,SSLSocketFactory的,代理服务器,布尔,INT)线:128
HttpEngine.openSocketConnection()线:316 HttpEngine.connect()线:311
HttpEngine .sendSocketRequest()行:290
HttpEngine.sendRequest()line:240
HttpURLConnectionImpl.connect()line:81
StartActivity。方法.invokeNative(Object,Object [],Class,Class [],Class,int,boolean)line:不可用[native方法isConnectedToServer(String,int)line:37 startActivity.connectionReturn ]
Method.invoke(对象,对象...)线:511
查看$ 1.onClick(查看)线:3592 按钮(查看).performClick()行:4202
查看$ PerformClick.run()行:17340 Handler.handleCallback(消息)线:725
ViewRootImpl $ ViewRootHandler(处理程序).dispatchMessage(消息)线:92 Looper.loop()线:137 ActivityThread.main(字符串[])线:50 Method.invokeNative(Object,Object [],Class,Class [],Class,int,boolean)line:不可用[本机方法]
Method.invoke(Object,Object ...)line:511
ZygoteInit $ MethodAndArgsCaller.run()线:793
ZygoteInit.main(字符串[])线:560 NativeStart.main(字符串[])行:不可用[本机方法]

+0

是提供日志猫! – RobinHood

+0

你有什么端口号? – dd619

回答

0

您可以使用此功能来了解链接是否已到,互联网连接或不

public boolean isConnected() { 
    try { 
     ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo netInfo = cm.getActiveNetworkInfo(); 

     if (netInfo != null && netInfo.isConnected()) { 
      // Network is available but check if we can get access from the 
      // network. 
      URL url = new URL("www.google.com"); 
      HttpURLConnection urlc = (HttpURLConnection) url 
        .openConnection(); 
      urlc.setRequestProperty("Connection", "close"); 
      urlc.setConnectTimeout(2000); // Timeout 2 seconds. 
      urlc.connect(); 

      if (urlc.getResponseCode() == 200) // Successful response. 
      { 
       return true; 
      } else { 
       Log.d("NO INTERNET", "NO INTERNET"); 
       showToast("URL down"); 
       return false; 
      } 
     } else { 
      showToast("No Internet Connection"); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return false; 
} 
0

记住这一点,当使用物业

的属性的值,"isConnectedToServer",是其实现方法具的名称d在您的活动,当用户点击这个按钮的系统调用。

打开Activity类(位于项目的src /目录下),并添加相应的方法:

/**当用户点击发送按钮*名为/

public void sendMessage(View view) { 
    // Do something in response to button 
} 

这就要求您导入View类:

为了让系统将此方法与android:onClick提供的方法名称相匹配,签名必须完全如图所示。具体而言,该方法必须:

1). Be public. 
2). Have a void return value. 
3). Have a View as the only parameter (this will be the View that was clicked).