解决方案 »
- android怎么得到通知栏的消息内容,然后保存消息
- 求助啊,明明有adb,为什么不能运行啊
- 请教一个关于xml 布局的问题
- 如何去掉几个ImageButton之间的空隙
- connect failed: EHOSTUNREACH (No route to host)
- ListView加载图片图片总是在第一个位置显示完第1,2,3,4张图片后,再依次在2,3,4位置显示对应的图片
- 如何辨别是否为山寨应用
- 为什么70行编译都不能成功? 什么错误啊 谢谢
- 跪求大神大牛们帮帮菜鸟小妹,急急急
- 用SnapDragon Profiler的时候发现GPU渲染每帧之间都有几十毫秒的中断
- 鄙人做了一个小软件,想添加发送短信功能,请问如何调用通讯录发短信,联系人的layout需不需要自己写
- android程序运行出现low memory 问题
服务的onBind() 方法应该被实现用作根据收到的意图(传入bindService()的意图),决定接受或拒绝连接。
如果连接被接受,它返回一个Stub的子类。如果服务接受了连接,Android调用客户端的onServiceConnected() 方法并传入一个IBinder对象,由服务管理的Stub子类的代理。通过该代理,客户端可以调用远程服务。
上述简单的描述忽略了一些RPC机制的细节。更多信息参见用AIDL设计远程接口和IBinder 类的描述。 在Android中, 每个应用程序都可以有自己的进程. 在写UI应用的时候, 经常要用到Service. 在不同的进程中, 怎样传递对象呢? 显然, Java中不允许跨进程内存共享. 因此传递对象, 只能把对象拆分成操作系统能理解的简单形式, 以达到跨界对象访问的目的. 在J2EE中,采用RMI的方式, 可以通过序列化传递对象. 在Android中, 则采用AIDL的方式. 理论上AIDL可以传递Bundle,实际上做起来却比较麻烦.AIDL(AndRoid接口描述语言)是一种借口描述语言; 编译器可以通过aidl文件生成一段代码,通过预先定义的接口达到两个进程内部通信进程的目的. 如果需要在一个Activity中, 访问另一个Service中的某个对象, 需要先将对象转化成AIDL可识别的参数(可能是多个参数), 然后使用AIDL来传递这些参数, 在消息的接收端, 使用这些参数组装成自己需要的对象.AIDL的IPC的机制和COM或CORBA类似, 是基于接口的,但它是轻量级的。它使用代理类在客户端和实现层间传递值. 如果要使用AIDL, 需要完成2件事情: 1. 引入AIDL的相关类.; 2. 调用aidl产生的class.
final static String SOAP_ACTION = "http://www.XXX.com";
private static final String NAMESPACE = "http://www.XXX.com/";
private static final String URL = "http://192.168.61.160/webserver/OperatingCenterService.asmx";
public static boolean isFirstLogin(String loginid)
{
/*是不是第一次登录,是返回真*/
String url = URL + "/FirstLogin";
HttpPost request = new HttpPost(url);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("loginid", loginid));
try { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,
HTTP.UTF_8);
request.setEntity(entity);
HttpResponse response = new DefaultHttpClient().execute(request); if (response.getStatusLine().getStatusCode() == 200) {
// ParserMachine.parse_onefirstLogin是对response.getEntity()的解析过程。
return ParserMachine.parse_onefirstLogin(EntityUtils.toString(response
.getEntity()));
} else {
return false;
} } catch (Exception e) { return false;
}
}
Cursor cur = null; String HTTP_HOST = "http://www.pvtool.com";
String loc_id, parent_id;
String loc_name;
float yearsunrate;
int sunratetime;
int maxsunratetime; maxsunratetime = 0;
try {
cur = this.db.rawQuery("SELECT theValue FROM sys_conf WHERE theVar=?", new String[]{ "sunratetime" });
cur.moveToFirst();
if (!cur.isAfterLast())
maxsunratetime = cur.getInt(0);
} catch (Exception e) {
e.printStackTrace();
}finally {
cur.close();
}
String content = getUrlContent(String.format(HTTP_HOST+"/forum/sunratexml.php?ud=%d", maxsunratetime)); try {
JSONArray locs = new JSONArray(content);
for (int i=0;i < locs.length(); i++) {
JSONObject loc = locs.getJSONObject(i);
loc_id = loc.getString("location_id");
parent_id = loc.getString("parent_id");
loc_name = loc.getString("location_name");
yearsunrate = loc.getLong("yearsunrate");
sunratetime = loc.getInt("sunratetime");
if (sunratetime>maxsunratetime)
maxsunratetime = sunratetime;
try {
cur = db.rawQuery("SELECT location_id FROM sunrate WHERE location_id=?",
new String[] { loc_id }); cur.moveToFirst();
if (!cur.isAfterLast())
db.execSQL("UPDATE sunrate SET avgtime=? WHERE location_id=?",
new Object[] { yearsunrate, loc_id });
else
db.execSQL("INSERT INTO sunrate(avgtime,city,location_id,parent_id) VALUES(?,?,?,?)",
new Object[] { yearsunrate, loc_name, loc_id, parent_id });
} finally {
cur.close();
}
db.execSQL("UPDATE sunrate SET theValue=? WHERE theVar=?",
new Object[] { yearsunrate, loc_id });
}
db.execSQL("UPDATE sys_conf SET theValue=? WHERE theVar=?",
new Object[] { maxsunratetime, "sunratetime" });
//java和php一样,TimeStamp都是以1970-01-01 00:00:00.000开始计算
Toast.makeText(context, new SimpleDateFormat("最新数据时间:yyyy年MM月dd日 HH:mm").format(new Timestamp(maxsunratetime)), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
throw new ParseException("Problem parsing API response", e);
}
} protected static synchronized String getUrlContent(String url)
throws ApiException {
if (sUserAgent == null) {
throw new ApiException("User-Agent string must be prepared");
} Log.i(TAG, "URL:"+url);
//HttpParams httpParameters = new BasicHttpParams();
//HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
//HttpConnectionParams.setSoTimeout(httpParameters, 5000);
//HttpClient client = new DefaultHttpClient(httpParameters);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
request.setHeader("User-Agent", sUserAgent); // 设置客户端标识 try {
HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine();
if (status.getStatusCode() != 200) {
throw new ApiException("Invalid response from server: "
+ status.toString());
} HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent(); // 获取HTTP返回的数据流 ByteArrayOutputStream content = new ByteArrayOutputStream(); int readBytes = 0;
while ((readBytes = inputStream.read(sBuffer)) != -1) {
content.write(sBuffer, 0, readBytes); // 转化为字节数组流
} return new String(content.toByteArray()); // 从字节数组构建String
} catch (IOException e) {
throw new ApiException("Problem communicating with API", e);
}
}
protected static synchronized String putUrlContent(String url, Map<String, String> params, Map<String, File> files)
throws ApiException {
if (sUserAgent == null) {
throw new ApiException("User-Agent string must be prepared");
} Log.i(TAG, "PUTURL:"+url);
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
String data = "";
try {
URL uri = new URL(url);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(5 * 1000);
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许输出
conn.setUseCaches(false);
conn.setRequestMethod("POST"); //Post方式
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("User-Agent", sUserAgent); // 设置客户端标识
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
+ ";boundary=" + BOUNDARY);
// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\""
+ entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes()); // 发送文件数据
if (files != null)
for (Map.Entry<String, File> file : files.entrySet()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"fileupload\"; filename=\""
+ file.getKey() + "\"" + LINEND);
sb1.append("Content-Type: image/jpeg" + LINEND);
//sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes()); InputStream is = new FileInputStream(file.getValue());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
} is.close();
outStream.write(LINEND.getBytes());
}
// 请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
// 得到响应码
int res = conn.getResponseCode();
String line = null;
InputStream in = conn.getInputStream();
InputStreamReader isReader = new InputStreamReader(in);
BufferedReader bufReader = new BufferedReader(isReader);
while((line = bufReader.readLine())!=null)
data += line;
if (res != 200) {
throw new ApiException("Invalid response from server: "
+ data);
}
in.close();
outStream.close();
conn.disconnect();
} catch (IOException e) {
throw new ApiException("Problem communicating with API", e);
}
return data;
}
package com.jftt.et.network;import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.List;import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;import android.util.Log;import com.jftt.et.common.CONST;/**
* class name:HttpConnect<BR>
* class description:get something to web <BR>
* PS: <BR>
*
* @version 1.00 2011/09/21
* @author CODYY)peijiangping
*/
public class HttpConnect { private String url;
private HttpPost httpRequest;
private HttpResponse httpResponse;
private HttpParams httpParams;
private HttpClient httpClient; public HttpConnect(String url) {
this.url = url;
httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
CONST.HTTP_CONNECT_TIME_OUT);
HttpConnectionParams.setSoTimeout(httpParams,
CONST.HTTP_SOCKET_TIME_OUT);
httpClient = new DefaultHttpClient(httpParams);
} public InputStream getDataAsInputStream(List<NameValuePair> params) {
InputStream result = null;
try {
httpRequest = new HttpPost(url);
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
httpResponse = httpClient.execute(httpRequest); if (CONST.HTTP_OK == httpResponse.getStatusLine().getStatusCode()) {
result = httpResponse.getEntity().getContent();
} } catch (MalformedURLException e) {
// TODO Auto-generated catch block
Log.e(CONST.LOG_TAG, e.getMessage(), e);
return result;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(CONST.LOG_TAG, e.getMessage(), e);
return result;
}
return result;
} public String getDataAsString(List<NameValuePair> params) {
String result = null;
try {
httpRequest = new HttpPost(url);
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
httpResponse = httpClient.execute(httpRequest); if (CONST.HTTP_OK == httpResponse.getStatusLine().getStatusCode()) {
result = EntityUtils.toString(httpResponse.getEntity());
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
Log.e(CONST.LOG_TAG, e.getMessage(), e);
return result;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(CONST.LOG_TAG, e.getMessage(), e);
return result;
}
return result;
} public int getDataAsInt(List<NameValuePair> params) {
int result = CONST.HTTP_ERROR;
try {
httpRequest = new HttpPost(url);
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
httpResponse = httpClient.execute(httpRequest); if (CONST.HTTP_OK == httpResponse.getStatusLine().getStatusCode()) {
result = Integer.parseInt(EntityUtils.toString(httpResponse
.getEntity()));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
Log.e(CONST.LOG_TAG, e.getMessage(), e);
return result;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(CONST.LOG_TAG, e.getMessage(), e);
return result;
}
return result;
}}