@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取控件
listView = findViewById(R.id.listview);
//写获取网络请求的方法
getHttp();
if (NetUtile.net(MainActivity.this)){
Toast.makeText(MainActivity.this,"网络连接成功",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this,"没网呀",Toast.LENGTH_SHORT).show();
}
}
private void getHttp() {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL("http://api.expoon.com/AppNews/getNewsList/type/1/p/1");
//请求网络
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//设置请求方式
urlConnection.setRequestMethod("GET");
//设置连接超时
urlConnection.setConnectTimeout(5000);
//设置读取超时
urlConnection.setReadTimeout(5000);
//判断是否网络请求成功
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream stream = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String string = "";
while ((string = reader.readLine()) != null) {
builder.append(string);
}
Message message = new Message();
message.obj = builder.toString();
//发送消息
handler.sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
//类
public static boolean net(Context context){
//获取网络管理者
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info!=null){
return info.isAvailable();
}
return false;
};
网友评论