Android高级技巧(一)

<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第一行代码》的一些总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值