What is Application

本文介绍了Android应用开发中如何利用Application组件进行数据传递和缓存,探讨了使用Application进行数据管理的最佳实践,同时指出了可能遇到的内存泄漏等问题。
What is Application
  Application和Activity,Service一样是android框架的一个系统组件,当android程序启动时系统会创建一个 application对象,用来存储系统的一些信息。通常我们是不需要指定一个Application的,这时系统会自动帮我们创建,如果需要创建自己 的Application,也很简单创建一个类继承 Application并在manifest的application标签中进行注册(只需要给Application标签增加个name属性把自己的 Application的名字定入即可)。

  android系统会为每个程序运行时创建一个Application类的对象且仅创建一个,所以Application可以说是单例 (singleton)模式的一个类.且application对象的生命周期是整个程序中最长的,它的生命周期就等于这个程序的生命周期。因为它是全局 的单例的,所以在不同的Activity,Service中获得的对象都是同一个对象。所以通过Application来进行一些,数据传递,数据共享 等,数据缓存等操作。

  Data passing between components using Application
  假如有一个Activity A, 跳转到 Activity B ,并需要推荐一些数据,通常的作法是Intent.putExtra() 让Intent携带,或者有一个Bundle把信息加入Bundle让Intent推荐Bundle对象,实现传递。但这样作有一个问题在 于,Intent和Bundle所能携带的数据类型都是一些基本的数据类型,如果想实现复杂的数据传递就比较麻烦了,通常需要实现 Serializable或者Parcellable接口。这其实是Android的一种IPC数据传递的方法。如果我们的两个Activity在同一个 进程当中为什么还要这么麻烦呢,只要把需要传递的对象的引用传递过去就可以了。

  基本思路是这样的。在Application中创建一个HashMap ,以字符串为索引,Object为value这样我们的HashMap就可以存储任何类型的对象了。在Activity A中把需要传递的对象放入这个HashMap,然后通过Intent或者其它途经再把这人索引的字符串传递给Activity B ,Activity B 就可以根据这个字符串在HashMap中取出这个对象了。只要再向下转个型 ,就实现了对象的传递。

  Data caching in Application
  我一般会习惯在application中建立两个HashMap一个用于数据的传递,一个用于缓 存一些数据。比如有一个Activity需要从网站获取一些数据,获取完之后我们就可以把这个数据cache到Application 当中,当页面设置到其它Activity再回来的时候,就可以直接使用缓存好的数据了。但如果需要cache一些大量的数据,最好是cache一些软引用)SoftReference ,并把这些数据cache到本地rom上或者sd卡上。如果在application中的缓存不存在,从本地缓存查找,如果本地缓存的数据也不存在再从网 络上获取。


  PitFalls
  使用Application如果保存了一些不该保存的对象很容易导致内存泄漏。如果在Application的oncreate中执行比较 耗时的操作,将直接影响的程序的启动时间。不些清理工作不能依靠onTerminate完成,因为android会尽量让你的程序一直运行,所以很有可能 onTerminate不会被调用。

  MemoryLeak
  在Java中内存泄漏是只,某个(某些)对象已经不在被使用应该被gc所回收,但有一个对象持有这个对象的引用而阻止这个对象被回收。比如我 们通常会这样创建一个View TextView tv = new TextView(this);这里的this通常都是Activity。所以这个TextView就持有着这个Activity的引用。下面看张图 (Google IO 2011 ppt中抄得)
  通常情况下,当用户转动手机的时候,android会重新调用OnCreate()方法生成一个新的Activity,原来的 Activity应该被GC所回收。但如果有个对象比如一个View的作用域超过了这个Activity(比如有一个static对象或者我们把这个 View的引用放到了Application当中),这时候原来的Activity将不能被GC所回收,Activity本身又持有很多对象的引用,所以 整个Activity的内存被泄漏了。

  经常导致内存泄漏的一些原因:
  keeping a long-lived reference to a Context.持有一个context的对象,从而gc不能回收。

  1,一个View,的作用域超出了所在的Activity的作用域,比如一个static的View或者 把一个View cache到了application当中 etc
  2,某些与View关联的Drawable的作用域超出了Activity的作用域。
  3,Runnable对象:比如在一个Activity中启用了一个新线程去执行一个任务,在这期间这个Activity被系统回收了, 但Runnalbe的任务还没有执行完毕并持有Activity的引用而泄漏,但这种泄漏一般来泄漏一段时间,只有Runnalbe的线程执行完闭,这个 Activity又可以被正常回收了。
  4,内存类的对象作用域超出Activity的范围:比如定义了一个内存类来存储数据,又把这个内存类的对象传给了其它Activity 或者Service等。因为内部类的对象会持有当前类的引用,所以也就持有了Context的引用。解决方法是如果不需要当前的引用把内部类写成

static或者,把内部类抽取出来变成一个单独的类,或者把避免内部对象作用域超出Activity的作用域。


  out Of Memery Error 在android中每一个程序所分到的内存大小是有限的,如果超过了这个数就会报Out Of Memory Error。android给程序分配的内存大小与手机硬件有关,以下是一些手机的数据:
  G1:16M Droid:24 Nexus One:32M Xoom:48Ms
  所以尽量把程序中的一些大的数据cache到本地文件。以免内存使用量超标。

  Snippets
  1,通过Application在两个Activity间传递数据
  记得数据传递完成之后,把存放在application的HashMap中的数据remove掉,以免发生内存的泄漏。
### Understanding HTTP: What is HTTP and How Does It Work HTTP (HyperText Transfer Protocol) is the foundation of data communication on the World Wide Web. It is an application-layer protocol used to transfer data between a client (such as a web browser) and a server over the internet. HTTP defines how messages are formatted and transmitted, and it specifies the actions that web servers and browsers should take in response to various commands [^1]. At its core, HTTP operates as a request-response protocol. A client, such as a web browser, sends an HTTP request to a server. The server then processes the request and returns an HTTP response. This exchange typically involves the retrieval of web resources such as HTML documents, images, and other files . #### HTTP Request Methods HTTP supports several request methods, each serving a specific purpose. The most commonly used methods include: - **GET**: Retrieves data from the server. This is the most common method used to fetch web pages. - **POST**: Submits data to be processed to the server. It is often used in forms where users input data. - **PUT**: Replaces the current representation of a resource with the request payload. - **DELETE**: Deletes the specified resource. - **PATCH**: Applies partial modifications to a resource. Each request includes a request line, headers, and optionally a message body. The request line contains the method, the path to the resource, and the HTTP version. Headers provide additional information about the request or response, such as content type and length [^1]. #### HTTP Status Codes HTTP status codes are three-digit numbers returned by the server to indicate the outcome of the request. Some common status codes include: - **200 OK**: The request was successful. - **301 Moved Permanently**: The requested resource has been permanently moved to a new location. - **400 Bad Request**: The server could not understand the request due to invalid syntax. - **401 Unauthorized**: Authentication is required to access the resource. - **403 Forbidden**: The server understood the request but refuses to fulfill it. - **404 Not Found**: The requested resource could not be found. - **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request. #### How HTTP Works: A Simple Example When a user types a URL into a browser, the browser sends an HTTP request to the server hosting the website. The server processes the request and sends back an HTTP response, which includes the requested resource (such as a web page) along with the appropriate status code. For example, if a user requests the homepage of a website, the browser might send a GET request like this: ``` GET / HTTP/1.1 Host: www.example.com ``` The server responds with an HTTP response like this: ``` HTTP/1.1 200 OK Content-Type: text/html Content-Length: 1234 <!DOCTYPE html> <html> <head> <title>Example Website</title> </head> <body> <h1>Welcome to Example Website</h1> </body> </html> ``` The browser then renders the HTML content and displays it to the user . #### HTTP vs. HTTPS HTTP is inherently insecure because data is transmitted in plain text, making it vulnerable to interception. HTTPS (HyperText Transfer Protocol Secure) addresses this issue by encrypting the data using SSL/TLS protocols. This ensures that the data remains private and secure during transmission . #### HTTP Versions Over the years, HTTP has evolved to improve performance and efficiency. The main versions include: - **HTTP/1.0**: The original version, which opened a new TCP connection for each request-response cycle. This led to latency issues. - **HTTP/1.1**: Introduced persistent connections, allowing multiple requests and responses to be sent over a single connection. This significantly improved performance . - **HTTP/2**: Built on the SPDY protocol, HTTP/2 introduced features such as multiplexing, header compression, and server push to further enhance performance [^1]. - **HTTP/3**: The latest version, which uses the QUIC protocol instead of TCP to reduce latency and improve connection reliability . #### Conclusion HTTP is a critical protocol that enables the seamless exchange of data on the web. Understanding its fundamentals helps in building efficient web applications and troubleshooting issues related to data transmission. ```python # Example of sending an HTTP GET request using Python's requests library import requests response = requests.get('https://www.example.com') print(f"Status Code: {response.status_code}") print(f"Response Body: {response.text}") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值