当前位置:首页 » 安卓系统 » 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" 内边距

热点内容
python查看进程 发布:2024-05-19 22:59:37 浏览:158
androidhtml颜色 发布:2024-05-19 22:58:34 浏览:847
米3系统存储和内存设备 发布:2024-05-19 22:50:50 浏览:214
途乐有哪些越野配置 发布:2024-05-19 22:49:53 浏览:673
php检测变量 发布:2024-05-19 22:45:31 浏览:322
结构与算法 发布:2024-05-19 22:32:22 浏览:588
ubuntuphp版本 发布:2024-05-19 21:59:12 浏览:929
解压文案馆 发布:2024-05-19 21:58:54 浏览:871
苏宁访问数 发布:2024-05-19 21:53:49 浏览:581
湿地下载ftp 发布:2024-05-19 21:46:10 浏览:487