Android的Http网络请求模型初步
-----------------------------------------------------
ActionBar在2.X等低版本下的兼容使用
ActionBar是Google官方在3.0版本,即API 11版本开始添加进SDK的,替代了原来的标题栏。
由于自从3.0开始,到现在4.1版本的手机,Android设备去掉了原来的menu键,原来的menu内容改为显示在ActionBar上面.
那么,有没有一种兼容方法,可以使应用在1.X,2.X设备可以使用menu键呼出,到4.X版本可以显示在ActionBar上面呢?
答案来自developer.android.com。
以下代码需要引入android-support-v(4 or 13).jar,可以在android-sdk-windows\extras\android\support\目录下找到
然后还需要在AndroidManifest.xml中配置targetSdkVersion属性
Android系统默认支持两种方式进行网络通信,来自Apache的HttpClient和Java自身的HttpURLConnection,官方文档显示自从GingerBread版本即2.3开始推荐使用HttpURLConnection,因为它代码更精简,bug也更少,但在之前版本有一些bug
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
private
HttpClient httpClient;
private
HttpEntity httpEntity;
private
HttpResponse httpResponse;
private
HttpPost httpPost;
private
static
final
int
TIMEOUT =
10000
;
private
static
final
String TAG =
"HttpManager"
;
public
int
doPost(String url, Map<String, String> map)
{
try
{
httpClient =
new
DefaultHttpClient();
httpPost =
new
HttpPost(url);
//将map对象转成json格式,再转成String类型
JSONObject json =
new
JSONObject(map);
httpEntity =
new
StringEntity(json.toString(), HTTP.ISO_8859_1);
Log.d(TAG,
"json: "
+ json);
httpPost.setEntity(httpEntity);
httpResponse = httpClient.execute(httpPost);
int
code = httpResponse.getStatusLine().getStatusCode();
Log.d(TAG,
"code: "
+ code);
HttpEntity entity = httpResponse.getEntity();
StringBuilder builder =
new
StringBuilder();
BufferedReader reader =
new
BufferedReader(
new
InputStreamReader(entity.getContent(), HTTP.UTF_8));
String s;
while
((s = reader.readLine()) !=
null
)
{
builder.append(s);
}
int
result = Integer.parseInt(builder.toString());
Log.d(TAG,
"result: "
+ result);
return
result;
}
catch
(Exception e)
{
return
-
1
;
}
}
|
-----------------------------------------------------
ActionBar在2.X等低版本下的兼容使用
ActionBar是Google官方在3.0版本,即API 11版本开始添加进SDK的,替代了原来的标题栏。
由于自从3.0开始,到现在4.1版本的手机,Android设备去掉了原来的menu键,原来的menu内容改为显示在ActionBar上面.
那么,有没有一种兼容方法,可以使应用在1.X,2.X设备可以使用menu键呼出,到4.X版本可以显示在ActionBar上面呢?
答案来自developer.android.com。
以下代码需要引入android-support-v(4 or 13).jar,可以在android-sdk-windows\extras\android\support\目录下找到
01
02
03
04
05
06
07
08
|
@Override
public
boolean
onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options, menu);
MenuCompat.setShowAsAction(menu.findItem(R.id.action_search),
1
);
return
true
;
}
|
然后还需要在AndroidManifest.xml中配置targetSdkVersion属性
01
|
<uses-sdk android:minSdkVersion=
"4"
android:targetSdkVersion=
"11"
/>
|