當前位置:首頁 » 安卓系統 » androidparams

androidparams

發布時間: 2022-05-26 18:19:07

1. Android AsyncHttpClient通過RequestParams params類傳到伺服器的參數。伺服器該怎麼接受。

直接$data=$_POST['鍵名'];就可以在php端接收。

2. Android訪問網路數據的幾種方式Demo

Android應用經常會和伺服器端交互,這就需要手機客戶端發送網路請求,下面介紹四種常用網路請求方式,我這邊是通過Android單元測試來完成這四種方法的,還不清楚Android的單元測試的同學們請看Android開發技巧總結中的Android單元測試的步驟一文。
java.net包中的HttpURLConnection類
Get方式:
[java] view plainprint?
// Get方式請求
public static void requestByGet() throws Exception {
String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";
// 新建一個URL對象
URL url = new URL(path);
// 打開一個HttpURLConnection連接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
// 設置連接超時時間
urlConn.setConnectTimeout(5 * 1000);
// 開始連接
urlConn.connect();
// 判斷請求是否成功
if (urlConn.getResponseCode() == HTTP_200) {
// 獲取返回的數據
byte[] data = readStream(urlConn.getInputStream());
Log.i(TAG_GET, "Get方式請求成功,返回數據如下:");
Log.i(TAG_GET, new String(data, "UTF-8"));
} else {
Log.i(TAG_GET, "Get方式請求失敗");
}
// 關閉連接
urlConn.disconnect();
}
// Get方式請求
public static void requestByGet() throws Exception {
String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";
// 新建一個URL對象
URL url = new URL(path);
// 打開一個HttpURLConnection連接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
// 設置連接超時時間
urlConn.setConnectTimeout(5 * 1000);
// 開始連接
urlConn.connect();
// 判斷請求是否成功
if (urlConn.getResponseCode() == HTTP_200) {
// 獲取返回的數據
byte[] data = readStream(urlConn.getInputStream());
Log.i(TAG_GET, "Get方式請求成功,返回數據如下:");
Log.i(TAG_GET, new String(data, "UTF-8"));
} else {
Log.i(TAG_GET, "Get方式請求失敗");
}
// 關閉連接
urlConn.disconnect();
}

Post方式:
[java] view plainprint?
// Post方式請求
public static void requestByPost() throws Throwable {
String path = "https://reg.163.com/logins.jsp";
// 請求的參數轉換為byte數組
String params = "id=" + URLEncoder.encode("helloworld", "UTF-8")
+ "&pwd=" + URLEncoder.encode("android", "UTF-8");
byte[] postData = params.getBytes();
// 新建一個URL對象
URL url = new URL(path);
// 打開一個HttpURLConnection連接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
// 設置連接超時時間
urlConn.setConnectTimeout(5 * 1000);
// Post請求必須設置允許輸出
urlConn.setDoOutput(true);
// Post請求不能使用緩存
urlConn.setUseCaches(false);
// 設置為Post請求
urlConn.setRequestMethod("POST");
urlConn.setInstanceFollowRedirects(true);
// 配置請求Content-Type
urlConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencode");
// 開始連接
urlConn.connect();
// 發送請求參數
DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
dos.write(postData);
dos.flush();
dos.close();
// 判斷請求是否成功
if (urlConn.getResponseCode() == HTTP_200) {
// 獲取返回的數據
byte[] data = readStream(urlConn.getInputStream());
Log.i(TAG_POST, "Post請求方式成功,返回數據如下:");
Log.i(TAG_POST, new String(data, "UTF-8"));
} else {
Log.i(TAG_POST, "Post方式請求失敗");
}
}
// Post方式請求
public static void requestByPost() throws Throwable {
String path = "https://reg.163.com/logins.jsp";
// 請求的參數轉換為byte數組
String params = "id=" + URLEncoder.encode("helloworld", "UTF-8")
+ "&pwd=" + URLEncoder.encode("android", "UTF-8");
byte[] postData = params.getBytes();
// 新建一個URL對象
URL url = new URL(path);
// 打開一個HttpURLConnection連接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
// 設置連接超時時間
urlConn.setConnectTimeout(5 * 1000);
// Post請求必須設置允許輸出
urlConn.setDoOutput(true);
// Post請求不能使用緩存
urlConn.setUseCaches(false);
// 設置為Post請求
urlConn.setRequestMethod("POST");
urlConn.setInstanceFollowRedirects(true);
// 配置請求Content-Type
urlConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencode");
// 開始連接
urlConn.connect();
// 發送請求參數
DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
dos.write(postData);
dos.flush();
dos.close();
// 判斷請求是否成功
if (urlConn.getResponseCode() == HTTP_200) {
// 獲取返回的數據
byte[] data = readStream(urlConn.getInputStream());
Log.i(TAG_POST, "Post請求方式成功,返回數據如下:");
Log.i(TAG_POST, new String(data, "UTF-8"));
} else {
Log.i(TAG_POST, "Post方式請求失敗");
}
}

org.apache.http包中的HttpGet和HttpPost類

Get方式:

[java] view plainprint?
// HttpGet方式請求
public static void requestByHttpGet() throws Exception {
String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";
// 新建HttpGet對象
HttpGet httpGet = new HttpGet(path);
// 獲取HttpClient對象
HttpClient httpClient = new DefaultHttpClient();
// 獲取HttpResponse實例
HttpResponse httpResp = httpClient.execute(httpGet);
// 判斷是夠請求成功
if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {
// 獲取返回的數據
String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
Log.i(TAG_HTTPGET, "HttpGet方式請求成功,返回數據如下:");
Log.i(TAG_HTTPGET, result);
} else {
Log.i(TAG_HTTPGET, "HttpGet方式請求失敗");
}
}
// HttpGet方式請求
public static void requestByHttpGet() throws Exception {
String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";
// 新建HttpGet對象
HttpGet httpGet = new HttpGet(path);
// 獲取HttpClient對象
HttpClient httpClient = new DefaultHttpClient();
// 獲取HttpResponse實例
HttpResponse httpResp = httpClient.execute(httpGet);
// 判斷是夠請求成功
if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {
// 獲取返回的數據
String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
Log.i(TAG_HTTPGET, "HttpGet方式請求成功,返回數據如下:");
Log.i(TAG_HTTPGET, result);
} else {
Log.i(TAG_HTTPGET, "HttpGet方式請求失敗");
}
}

Post方式:
[java] view plainprint?
// HttpPost方式請求
public static void requestByHttpPost() throws Exception {
String path = "https://reg.163.com/logins.jsp";
// 新建HttpPost對象
HttpPost httpPost = new HttpPost(path);
// Post參數
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", "helloworld"));
params.add(new BasicNameValuePair("pwd", "android"));
// 設置字元集
HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
// 設置參數實體
httpPost.setEntity(entity);
// 獲取HttpClient對象
HttpClient httpClient = new DefaultHttpClient();
// 獲取HttpResponse實例
HttpResponse httpResp = httpClient.execute(httpPost);
// 判斷是夠請求成功
if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {
// 獲取返回的數據
String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
Log.i(TAG_HTTPGET, "HttpPost方式請求成功,返回數據如下:");
Log.i(TAG_HTTPGET, result);
} else {
Log.i(TAG_HTTPGET, "HttpPost方式請求失敗");
}
}

3. android addContentView(view, params)

params這個參數不就是設置大小的么,然後用設置坐標的方法,設置空間的layout_x和layout_y

4. android什麼叫非同步請求,怎麼實現

一.非同步請求主要解決線程無法更新UI組件的方案

使用Handler實現線程之間的通信。

Activity.runOnUiThread(Runnbale)

View.post(Runnable)

View.postDelayed(Runnable)

二.ANR異常

Android默認約定當UI線程阻塞超過20秒將會引發ANR異常。開發者必須牢記,不要在UI線程中執行一些耗時操作

三.AsyncTask抽象類

AsyncTask<Params,Progress,Result>是一個抽象類,通常用於被繼承,繼承AsyncTask需要指定三個泛型參數:

Params:啟動任務執行的輸入參數的類型

Progress:後台任務完成進度值得類型

Result:後台執行任務完成後返回結果的類型

四.AsyncTask的特點

更輕量一些,適用於簡單的非同步處理,不需要藉助線程和Handler即可

五.使用AsyncTask的步驟

  1. 創建AsyncTask的子類,並為三個泛型參數指定類型,如果某個泛型參數不需要指定類型,可將它設為Void

  2. 根據需要,實現AsyncTask的如下方法:

    doInBackground(Params...):後台線程將要完成的任務,可以調用publishProgress(Porgress...values)方法更新任務執行進度。

    onProgressUpdate(Porgress..values):在doInBackground()方法中調用publishPorgress()方法更新任務的執行進度後,就會觸發該方法

    onPreExecute():執行後台耗時操作前被調用,通常用戶完成一些初始化操作,比如在界面上顯示進度條

    onPostExecute(Result result):當doInBackground()完成後,系統會自動調用onPostExecute()方法,並將doInBackground()方法返回的值傳給該方法.

  3. 調用AsyncTask子類的實例的execute(Params...params)開始執行耗時任務

六.使用AsyncTask時必須遵守的規則

必須在UI中創建AsyncTask的實例

必須在UI線程中調用AsyncTask的execute()方法

AsyncTask的onPreExecute()、onPostExecute(Result result)、doInBackground(Params....params)、onProgressUpdate(Progress...values)方法,不應該由程序員代碼調用,而是由AsyncTask系統負責調用

每個AsyncTask只能被執行一次,多次調用將會引發異常。

5. android 動態設置布局寬度

例如設置一個圖片寬高 關鍵代碼:
//取控制項當前的布局參數
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) imageView.getLayoutParams();
//設置寬度值
params.width = dip2px(MainActivity.this, width);
//設置高度值
params.height = dip2px(MainActivity.this, height);
//使設置好的布局參數應用到控制項
imageView.setLayoutParams(params);
1
2
3
4
5
6
7
8
1
2
3
4
5
6
7
8
高度除了可以設置成以上固定的值,也可以設置成wrap_content或match_content
ViewGroup.LayoutParams.WRAP_CONTENT
ViewGroup.LayoutParams.MATCH_PARENT
1
2
1
2
在這里插入圖片描述
xml

6. android怎麼在網路請求頭里加參數

android中網路通信分為socket編程和http編程,這里只介紹htt方面。網路請求方式可分為get請求,post兩種請求方式,GET方式在進行數據請求時,會把數據附加到URL後面傳遞給伺服器,比如常見的:http://XXX.XXX.XXX/XX.aspx?id=1,POST方式則是將請求的數據放到HTTP請求頭中,作為請求頭的一部分傳入伺服器。
所以,在進行HTTP編程前,首先要明確究竟使用的哪種方式進行數據請求的。

android中Http編程有兩種:1、HttpURLConnection;2、HttpClient

首先介紹一下HttpURLConnection方式的get請求和post請求方法:

[java] view
plainprint?

private Map<String, String> paramsValue;

String urlPath=null;// 發送地http://192.168.100.91:8080/myweb/login?username=abc&password=123

public void initData(){urlPath="http://192.168.100.91:8080/myweb/login";

paramsValue=new HashMap<String, String>();

paramsValue.put("username", "111");

paramsValue.put("password", "222");

}


private Map<String, String> paramsValue;
String urlPath=null;

// 發送地http://192.168.100.91:8080/myweb/login?username=abc&password=123
public void initData(){

urlPath="http://192.168.100.91:8080/myweb/login";
paramsValue=new HashMap<String, String>();
paramsValue.put("username", "111");
paramsValue.put("password", "222");
}

get方式發起請求:

[java] view
plainprint?

private boolean sendGETRequest(String path, Map<String, String> params) throws Exception {

boolean success=false;// StringBuilder是用來組拼請求地址和參數

StringBuilder sb = new StringBuilder();

sb.append(path).append("?");

if (params != null && params.size() != 0) {

for (Map.Entry<String, String> entry : params.entrySet()) {

// 如果請求參數中有中文,需要進行URLEncoder編碼 gbk/utf8

sb.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "utf-8"));

sb.append("&");

}

sb.deleteCharAt(sb.length() - 1);

}URL url = new URL(sb.toString());

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(20000);

conn.setRequestMethod("GET");if (conn.getResponseCode() == 200) {

success= true;

}

if(conn!=null)

conn.disconnect();

return success;

}
private boolean sendGETRequest(String path, Map<String, String> params) throws Exception {
boolean success=false;

// StringBuilder是用來組拼請求地址和參數
StringBuilder sb = new StringBuilder();
sb.append(path).append("?");
if (params != null && params.size() != 0) {
for (Map.Entry<String, String> entry : params.entrySet()) {
// 如果請求參數中有中文,需要進行URLEncoder編碼 gbk/utf8
sb.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "utf-8"));
sb.append("&");
}
sb.deleteCharAt(sb.length() - 1);
}

URL url = new URL(sb.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(20000);
conn.setRequestMethod("GET");

if (conn.getResponseCode() == 200) {
success= true;
}
if(conn!=null)
conn.disconnect();
return success;
}

postt方式發起請求:

[java] view
plainprint?

private boolean sendPOSTRequest(String path,Map<String, String> params) throws Exception{

boolean success=false;

//StringBuilder是用來組拼請求參數

StringBuilder sb = new StringBuilder();if(params!=null &¶ms.size()!=0){for (Map.Entry<String, String> entry : params.entrySet()) {sb.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "utf-8"));

sb.append("&");}

sb.deleteCharAt(sb.length()-1);

}//entity為請求體部分內容

//如果有中文則以UTF-8編碼為username=%E4%B8%AD%E5%9B%BD&password=123

byte[] entity = sb.toString().getBytes();URL url = new URL(path);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(2000);

// 設置以POST方式

conn.setRequestMethod("POST");

// Post 請求不能使用緩存

// urlConn.setUseCaches(false);

//要向外輸出數據,要設置這個

conn.setDoOutput(true);

// 配置本次連接的Content-type,配置為application/x-www-form-urlencoded

//設置content-type獲得輸出流,便於想伺服器發送信息。

//POST請求這個一定要設置

conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

conn.setRequestProperty("Content-Length", entity.length+"");

// 要注意的是connection.getOutputStream會隱含的進行connect。

OutputStream out = conn.getOutputStream();

//寫入參數值

out.write(entity);

//刷新、關閉

out.flush();

out.close();if (conn.getResponseCode() == 200) {

success= true;

}

if(conn!=null)

conn.disconnect();

return success;}
private boolean sendPOSTRequest(String path,Map<String, String> params) throws Exception{
boolean success=false;
//StringBuilder是用來組拼請求參數
StringBuilder sb = new StringBuilder();

if(params!=null &¶ms.size()!=0){

for (Map.Entry<String, String> entry : params.entrySet()) {

sb.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "utf-8"));
sb.append("&");

}
sb.deleteCharAt(sb.length()-1);
}

//entity為請求體部分內容
//如果有中文則以UTF-8編碼為username=%E4%B8%AD%E5%9B%BD&password=123
byte[] entity = sb.toString().getBytes();

URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(2000);
// 設置以POST方式
conn.setRequestMethod("POST");
// Post 請求不能使用緩存
// urlConn.setUseCaches(false);
//要向外輸出數據,要設置這個
conn.setDoOutput(true);
// 配置本次連接的Content-type,配置為application/x-www-form-urlencoded
//設置content-type獲得輸出流,便於想伺服器發送信息。
//POST請求這個一定要設置
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", entity.length+"");
// 要注意的是connection.getOutputStream會隱含的進行connect。
OutputStream out = conn.getOutputStream();
//寫入參數值
out.write(entity);
//刷新、關閉
out.flush();
out.close();

if (conn.getResponseCode() == 200) {
success= true;
}
if(conn!=null)
conn.disconnect();
return success;

}

在介紹一下HttpClient方式,相比HttpURLConnection,HttpClient封裝的得更簡單易用一些,看一下實例:

get方式發起請求:

[java] view
plainprint?

public String getRequest(String UrlPath,Map<String, String> params){

String content=null;

StringBuilder buf = new StringBuilder();

if(params!=null &¶ms.size()!=0){for (Map.Entry<String, String> entry : params.entrySet()) {buf.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "utf-8"));

buf.append("&");}

buf.deleteCharAt(buf.length()-1);

}

content= buf.toString();HttpClient httpClient = new DefaultHttpClient();

HttpGet getMethod = new HttpGet(content);HttpResponse response = null;

try {

response = httpClient.execute(getMethod);

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}catch (Exception e) {

e.printStackTrace();

}if (response!=null&&response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

try {

content = EntityUtils.toString(response.getEntity());

} catch (ParseException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}return content;

}
public String getRequest(String UrlPath,Map<String, String> params){
String content=null;
StringBuilder buf = new StringBuilder();
if(params!=null &¶ms.size()!=0){

for (Map.Entry<String, String> entry : params.entrySet()) {

buf.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "utf-8"));
buf.append("&");

}
buf.deleteCharAt(buf.length()-1);
}
content= buf.toString();

HttpClient httpClient = new DefaultHttpClient();
HttpGet getMethod = new HttpGet(content);

HttpResponse response = null;
try {
response = httpClient.execute(getMethod);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}

if (response!=null&&response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
try {
content = EntityUtils.toString(response.getEntity());
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

return content;
}

postt方式發起請求:

[java] view
plainprint?

private boolean sendPOSTRequestHttpClient(String path,Map<String, String> params) throws Exception {

boolean success = false;

// 封裝請求參數

List<NameValuePair> pair = new ArrayList<NameValuePair>();

if (params != null && !params.isEmpty()) {

for (Map.Entry<String, String> entry : params.entrySet()) {

pair.add(new BasicNameValuePair(entry.getKey(), entry

.getValue()));

}

}

// 把請求參數變成請求體部分

UrlEncodedFormEntity uee = new UrlEncodedFormEntity(pair, "utf-8");

// 使用HttpPost對象設置發送的URL路徑

HttpPost post = new HttpPost(path);

// 發送請求體

post.setEntity(uee);

// 創建一個瀏覽器對象,以把POST對象向伺服器發送,並返回響應消息

DefaultHttpClient dhc = new DefaultHttpClient();

HttpResponse response = dhc.execute(post);

if (response.getStatusLine().getStatusCode() == 200) {

success = true;

}

return success;

}
private boolean sendPOSTRequestHttpClient(String path,Map<String, String> params) throws Exception {
boolean success = false;
// 封裝請求參數
List<NameValuePair> pair = new ArrayList<NameValuePair>();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
pair.add(new BasicNameValuePair(entry.getKey(), entry
.getValue()));
}
}
// 把請求參數變成請求體部分
UrlEncodedFormEntity uee = new UrlEncodedFormEntity(pair, "utf-8");
// 使用HttpPost對象設置發送的URL路徑
HttpPost post = new HttpPost(path);
// 發送請求體
post.setEntity(uee);
// 創建一個瀏覽器對象,以把POST對象向伺服器發送,並返回響應消息
DefaultHttpClient dhc = new DefaultHttpClient();
HttpResponse response = dhc.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
success = true;
}
return success;
}

7. android 怎麼發送post請求並接收二進制數據

可使用android自帶的httpclient框架實現向伺服器發起get或post請求,以下為完整的示例代碼:
1. GET 方式傳遞參數
//先將參數放入List,再對參數進行URL編碼
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("param1", "數據")); //增加參數1
params.add(new BasicNameValuePair("param2", "value2"));//增加參數2
String param = URLEncodedUtils.format(params, "UTF-8");//對參數編碼
String baseUrl = "伺服器介面完整URL";
HttpGet getMethod = new HttpGet(baseUrl + "?" + param);//將URL與參數拼接
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(getMethod); //發起GET請求
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //獲取響應碼
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"));//獲取伺服器響應內容
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

2. POST方式 方式傳遞參數
//和GET方式一樣,先將參數放入List
params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("param1", "Post方法"));//增加參數1
params.add(new BasicNameValuePair("param2", "第二個參數"));//增加參數2
try {
HttpPost postMethod = new HttpPost(baseUrl);//創建一個post請求
postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //將參數填入POST Entity中
HttpResponse response = httpClient.execute(postMethod); //執行POST方法
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //獲取響應碼
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8")); //獲取響應內容
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

8. 請簡述什麼是android事件處理,並分析兩種android事件處理機制的實現過程和區別

UI編程通常都會伴隨事件處理,Android也不例外,它提供了兩種方式的事件處理:基於回調的事件處理和基於監聽器的事件處理。

對於基於監聽器的事件處理而言,主要就是為Android界面組件綁定特定的事件監聽器;對於基於回調的事件處理而言,主要做法是重寫Android組件特定的回調函數,Android大部分界面組件都提供了事件響應的回調函數,我們主要重寫它們就行。


一 基於監聽器的事件處理

相比於基於回調的事件處理,這是更具「面向對象」性質的事件處理方式。在監聽器模型中,主要涉及三類對象:

1)事件源Event Source:產生事件的來源,通常是各種組件,如按鈕,窗口等。

2)事件Event:事件封裝了界面組件上發生的特定事件的具體信息,如果監聽器需要獲取界面組件上所發生事件的相關信息,一般通過事件Event對象來傳遞。

3)事件監聽器Event Listener:負責監聽事件源發生的事件,並對不同的事件做相應的處理。


基於監聽器的事件處理機制是一種委派式Delegation的事件處理方式,事件源將整個事件委託給事件監聽器,由監聽器對事件進行響應處理。這種處理方式將事件源和事件監聽器分離,有利於提供程序的可維護性。

舉例:

View類中的OnLongClickListener監聽器定義如下:(不需要傳遞事件)


[java] view plainprint?

public interface OnLongClickListener {

boolean onLongClick(View v);

}

public interface OnLongClickListener {
boolean onLongClick(View v);
}


View類中的OnLongClickListener監聽器定義如下:(需要傳遞事件MotionEvent)

[java] view plainprint?

public interface OnTouchListener {

boolean onTouch(View v, MotionEvent event);

}

public interface OnTouchListener {
boolean onTouch(View v, MotionEvent event);
}

二 基於回調的事件處理

相比基於監聽器的事件處理模型,基於回調的事件處理模型要簡單些,該模型中,事件源和事件監聽器是合一的,也就是說沒有獨立的事件監聽器存在。當用戶在GUI組件上觸發某事件時,由該組件自身特定的函數負責處理該事件。通常通過重寫Override組件類的事件處理函數實現事件的處理。

舉例:

View類實現了KeyEvent.Callback介面中的一系列回調函數,因此,基於回調的事件處理機制通過自定義View來實現,自定義View時重寫這些事件處理方法即可。

[java] view plainprint?

public interface Callback {

// 幾乎所有基於回調的事件處理函數都會返回一個boolean類型值,該返回值用於

// 標識該處理函數是否能完全處理該事件

// 返回true,表明該函數已完全處理該事件,該事件不會傳播出去

// 返回false,表明該函數未完全處理該事件,該事件會傳播出去

boolean onKeyDown(int keyCode, KeyEvent event);

boolean onKeyLongPress(int keyCode, KeyEvent event);

boolean onKeyUp(int keyCode, KeyEvent event);

boolean onKeyMultiple(int keyCode, int count, KeyEvent event);

}

public interface Callback {
// 幾乎所有基於回調的事件處理函數都會返回一個boolean類型值,該返回值用於
// 標識該處理函數是否能完全處理該事件
// 返回true,表明該函數已完全處理該事件,該事件不會傳播出去
// 返回false,表明該函數未完全處理該事件,該事件會傳播出去
boolean onKeyDown(int keyCode, KeyEvent event);
boolean onKeyLongPress(int keyCode, KeyEvent event);
boolean onKeyUp(int keyCode, KeyEvent event);
boolean onKeyMultiple(int keyCode, int count, KeyEvent event);
}

三 比對

基於監聽器的事件模型符合單一職責原則,事件源和事件監聽器分開實現;

Android的事件處理機制保證基於監聽器的事件處理會優先於基於回調的事件處理被觸發;

某些特定情況下,基於回調的事件處理機制會更好的提高程序的內聚性。


四 基於自定義監聽器的事件處理流程

在實際項目開發中,我們經常需要自定義監聽器來實現自定義業務流程的處理,而且一般都不是基於GUI界面作為事件源的。這里以常見的app自動更新為例進行說明,在自動更新過程中,會存在兩個狀態:下載中和下載完成,而我們的程序需要在這兩個狀態做不同的事情,「下載中」需要在UI界面上實時顯示軟體包下載的進度,「下載完成」後,取消進度條的顯示。這里進行一個模擬,重點在說明自定義監聽器的事件處理流程。

4.1)定義事件監聽器如下:

9. android 怎樣獲取後台的數據

可使用android自帶的httpclient框架,向後台發起請求,獲取數據。

1. GET 方式傳遞參數
//先將參數放入List,再對參數進行URL編碼
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("param1", "數據")); //增加參數1
params.add(new BasicNameValuePair("param2", "value2"));//增加參數2
String param = URLEncodedUtils.format(params, "UTF-8");//對參數編碼
String baseUrl = "伺服器介面完整URL";
HttpGet getMethod = new HttpGet(baseUrl + "?" + param);//將URL與參數拼接
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(getMethod); //發起GET請求
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //獲取響應碼
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"));//獲取伺服器響應內容
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

2. POST方式 方式傳遞參數
//和GET方式一樣,先將參數放入List
params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("param1", "Post方法"));//增加參數1
params.add(new BasicNameValuePair("param2", "第二個參數"));//增加參數2
try {
HttpPost postMethod = new HttpPost(baseUrl);//創建一個post請求
postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //將參數填入POST Entity中
HttpResponse response = httpClient.execute(postMethod); //執行POST方法
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //獲取響應碼
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8")); //獲取響應內容
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

10. Android為什麼設置params.bottomMargin無效

Android動態改變View控制項大小的方法:
1、聲明控制項參數獲取對象 LayoutParams lp;
2、獲取控制項參數: lp = 控制項id.getLayoutParams();
3、設置控制項參數:如高度。 lp.height -= 10;
4:、使設置生效:控制項id.setLayoutParams(lp);
例如如要把Imageview下移200px: ImageView.setPadding( ImageView.getPaddingLeft(), ImageView.getPaddingTop()+200, ImageView.getPaddingRight(), ImageView.getPaddingBottom());


控制項之間的間距有兩種設置:

  1. android:layout_margin="10dp" 外邊距

  2. android:padding="10dp" 內邊距

熱點內容
sql語句等於怎麼寫 發布:2024-05-07 18:05:46 瀏覽:815
我的世界電腦版第三方伺服器大全 發布:2024-05-07 18:00:46 瀏覽:625
主伺服器的ip地址 發布:2024-05-07 17:58:50 瀏覽:544
組伺服器打電腦游戲 發布:2024-05-07 17:46:19 瀏覽:865
java的文件路徑 發布:2024-05-07 16:55:29 瀏覽:293
雲表伺服器安裝導致電腦崩潰 發布:2024-05-07 15:58:35 瀏覽:524
ftp是什麼檢測器 發布:2024-05-07 15:37:59 瀏覽:403
重慶電信伺服器租用教學雲主機 發布:2024-05-07 15:28:05 瀏覽:73
python聲明對象 發布:2024-05-07 15:28:03 瀏覽:128
存儲過程的應用場景 發布:2024-05-07 15:12:16 瀏覽:613