标题可能没说明白 直接上代码 很简单
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 02234) {
/* Bundle bundle = new Bundle();
bundle.putInt("SocketTimeoutException",);*/
Toast.makeText(MainActivity.mactivity, "连接超时", Toast.LENGTH_SHORT).show();
}
}
};
public String urlCon(final String input) {
Message message = new Message();
try {
URL url = new URL(PATH + input);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5);
if (connection.getConnectTimeout() == 5000) {
message.what = 01234;
handler.sendEmptyMessage(message.what);
}
connection.setReadTimeout(8000);
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.flush();
connection.connect();
connection.getResponseCode();
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
Log.i("返回的数据是 ", response.toString());
dowmloadfile(String.valueOf(new InputStreamReader(in)));
return response.toString();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (ProtocolException e1) {
e1.printStackTrace();
} catch (SocketTimeoutException e1) {
message.what = 02234;
handler.sendEmptyMessage(message.what);
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
在外部类写了一个网络访问的函数,当捕捉到网络连接超时异常时发消息给Handler 然后再handler里面想做的是把catch到的SocketTimeoutException信息通过一个方法处理,处理之后可以让其他类得到这个信息,可以调用到这个信息,要怎么做呀?用bundle?还是什么函数来时间呢?求大神赐教啊!~~~~~~~
网络请求是一个异步的过程,你可以写一个静态方法调用,存储到map中,其它类要想获取响应的信息就去map那里获取就可以了
这个是完全可以的,不影响使用。
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 02234) {
SocketTimeoutException socketTimeoutException = new SocketTimeoutException();
map.put("key1", socketTimeoutException);
String s = Cloud.map.get("key1").toString();
System.out.println(s);
Toast.makeText(MainActivity.mactivity, "连接超时", Toast.LENGTH_SHORT).show();
}
}
};
空指针:获取s的时候Cloud.map这个好像没在你的代码里看到 创建Cloud实例或者给Cloud.map赋值耶