<span style="font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre"></span></span><pre name="code" class="java"><span style="white-space:pre"> </span>在Android项目中经常看到Myapplication这个类,初学者对于Application这个类接触并不多,其实在项目中Myapplication的最主要作用就是全局获取Context,初学者没有用到这个类主要是还没做过大项目,代码的逻辑层没有脱离activity类,当代码脱离Activity,而恰恰需要用到Context时候就需要用到了。
<span style="font-family: Arial, Helvetica, sans-serif;">public class HttpUtil</span>
{
private void sendHttpRequest() {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection conn = null;
try {
URL url = new URL("http://ww.baidu.com");
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
InputStream is = conn.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder();
String line;
while ((line=bufferedReader.readLine())!=null){
response.append(line);
}
Message msg = new Message();
msg.obj = response.toString();
msg.what = SHOW_RESPONSE;
handler.sendMessage(msg);
}catch (Exception e){
e.printStackTrace();
}finally {
if(conn!= null){
conn.disconnect();;
}
}
}
}).start();
}
}
比如在这个类需要用到toast这个方法时候就需要获取Context对象,如果直接传入这个参数到方法中的化只是单纯推卸责任给调用方,不利于代码的重用,下面就用Android提供的application类来完成全局获取Context
public class MyApplication extends Application
{
private static Context context;
@Override
public void onCreate(){
context = getApplicationContext();
}
public static Context getContext(){
return context;
}
}
然后需要在AndroidManifest.xml的<application>标签下进行指定就可以了,比如:android:name="com.example.network.MyApplication"
本文是《Android第一行代码》的一些总结