判断网络状态:
public static boolean isConnection(Context context) {
<span style="white-space:pre"> </span>ConnectivityManager cm =
<span style="white-space:pre"> </span>(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
<span style="white-space:pre"> </span>if(cm == null) {
<span style="white-space:pre"> </span>return false;
<span style="white-space:pre"> </span>} else {
<span style="white-space:pre"> </span>NetworkInfo[] info = cm.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>return false;
}
连接后台:(登录为例子)
/**
*
* @param urlPath http://localhost:8080/myWebSocket/login
* @param state 1,2,3
* @param name
* @param pw
* @param encode "utf-8"
* @return
* @throws IOException
* @throws ClientProtocolException
*/
public static String login(String urlPath,int state, String name,String pw,String encode) {
Log.i("main", "input");
List<NameValuePair> list =
new ArrayList<NameValuePair>();
BasicNameValuePair statePair =
new BasicNameValuePair("state", String.valueOf(state));
BasicNameValuePair namePair =
new BasicNameValuePair("loginName", name);
BasicNameValuePair pwPair =
new BasicNameValuePair("loginPw", pw);
list.add(statePair);
list.add(namePair);
list.add(pwPair);
try {
UrlEncodedFormEntity enity =
new UrlEncodedFormEntity(list,encode);
HttpPost httpPost = new HttpPost(urlPath);
httpPost.setEntity(enity);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
//获取响应
InputStream inputStream = httpResponse.getEntity().getContent();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
String result = "";
try {
if(inputStream != null) {
while( (len = inputStream.read(data)) != -1 ){
outputStream.write(data, 0, len);
}
result = new String(outputStream.toByteArray(), encode);
Log.i("main","result"+result);
return result;
}
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
Log.e("login http is error", "read http error");
} finally {
inputStream.close();
outputStream.close();
}
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
后台只需要写一个一般的登录web后台就可以,这里我使用的是servelet。不管web后台使用什么样的框架搭建只需要urlPath正确即可