先定义三个接口用来处理返回的数据;
public interface IHttpPostCompleted {
void onHttpPostCompleted(String responseText) ;
}
public interface IHttpPostError {
void onHttpPostError(int statusCode );
}
public interface IExecuteException {
void onExecuteException(Exception e);
}
-------------------------辅助类-------------------
public class UriImageCache {
public static String parse(String url) {
if (url == null || url == "")
return null;
String sk = url.toLowerCase();
String name = String.format("%d.imgdata", sk.hashCode() );
return getImagePath(name);
}
}
-----------------------上传下载的常用接口-----------------
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.http.AndroidHttpClient;
import android.util.Log;
public class urlhelper {
public static boolean checkUrl(String path) {
boolean ok = false;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(path);
try {
HttpResponse response = httpclient.execute(httppost);
int code = response.getStatusLine().getStatusCode();
ok = code == HttpStatus.SC_OK;
} catch (Exception e) {
}
return ok;
}
public static void doPost(String path, IHttpPostCompleted ready,
IHttpPostError error, IExecuteException exception) {
urlhelper.doPost(path, null, ready, error, exception);
}
public static void doPost(String actionUrl, Map<String, String> params,
IHttpPostCompleted ready, IHttpPostError error, IExecuteException exception
) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(actionUrl);
try {
if (params != null && params.isEmpty() == false) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
params.size());
for (Entry<String, String> enty : params.entrySet()) {
if (enty.getValue() == null) ///-------------这个不能丢
continue;
nameValuePairs.add(new BasicNameValuePair(enty.getKey(),
enty.getValue()));
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,
"UTF-8"));
httppost.setHeader("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
}
HttpResponse response = httpclient.execute(httppost);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
StringBuffer sb = new StringBuffer();
String sResponse = null;
while ((sResponse = reader.readLine()) != null) {
sb.append(sResponse);
}
if (ready != null) {
ready.onHttpPostCompleted(sb.toString());
}
} else {
if (error != null) {
error.onHttpPostError(code);
}
}
} catch (Exception e) {
if (exception != null) {
exception.onExecuteException(e);
}
}
}
/**
* 上传文件的接口
*
* @param actionUrl
* @param params
* @param imageFile
* @param ready
* @param error
* @param exception
*/
public static void doPost(String actionUrl, Map<String, String> params,
String filePath, IHttpPostCompleted ready, IHttpPostError error,
IExecuteException exception
) {
File file = new File(filePath);
if (file.exists() == false) {
if (exception != null) {
exception.onExecuteException(new Exception("文件不存在"));
}
return;
}
if (file.isFile() == false) {
if (exception != null) {
exception
.onExecuteException(new FileNotFoundException(filePath));
}
return;
}
if (file.canRead() == false) {
if (exception != null) {
exception.onExecuteException(new Exception("无文件读取权限"));
}
return;
}
if (file.length() == 0L) {
if (exception != null) {
exception.onExecuteException(new Exception("不可以上传空文件"));
}
return;
}
Bitmap bitmap = null;
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(actionUrl);
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
try {
if (params != null && params.size() > 0) {
for (Map.Entry<String, String> entry : params.entrySet()) {
String val = entry.getValue();
if (val == null)
continue;
entity.addPart(entry.getKey(), new StringBody(val));
}
}
entity.addPart("imagefile", new ByteArrayBody(data, file.getName()));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
StringBuffer sb = new StringBuffer();
String sResponse = reader.readLine();
while (sResponse != null) {
sb.append(sResponse);
sResponse = reader.readLine();
}
if (ready != null) {
ready.onHttpPostCompleted(sb.toString());
}
} else {
if (error != null) {
error.onHttpPostError(code);
}
}
} catch (Exception e) {
if (exception != null) {
exception.onExecuteException(e);
}
}
}
public static Bitmap downloadBitmap(String url) {
// AndroidHttpClient is not allowed to be used from the main thread
final String LogTag = "downloadBitmap";
final HttpClient client =new DefaultHttpClient(); // 可以换成 AndroidHttpClient
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode
+ " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
String phyicalPath = UriImageCache.parse(url);
FileOutputStream fos = new FileOutputStream(phyicalPath,
true);
DataHelper.copyStream(inputStream, fos);
// return BitmapFactory.decodeStream(inputStream);
// Bug on slow connections, fixed in future release.
return BitmapFactory.decodeFile(phyicalPath);
// return BitmapFactory.decodeStream(new
// FlushedInputStream(inputStream));
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (IOException e) {
getRequest.abort();
Log.w(LogTag, "I/O error while retrieving bitmap from " + url, e);
} catch (IllegalStateException e) {
getRequest.abort();
Log.w(LogTag, "Incorrect URL: " + url);
} catch (Exception e) {
getRequest.abort();
Log.w(LogTag,
"Error while retrieving bitmap from " + url, e);
} finally {
/* 用 AndroidHttpClient 时需要处理的数据
if ((client instanceof AndroidHttpClient)) {
((AndroidHttpClient) client).close();
}
*/
}
return null;
}
}
PS:-这些代码都是从网上,书上和自己做的项目中边学边改的,提取出来放在这里,希望对那位兄弟有用。。
边做边学吧。
-----------------------layout/async.xml--------------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:id="@+id/text2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/startTask"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="startTask"
/>
<ListView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/contentListView"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll">
</ListView>
</LinearLayout>
===============================用来模拟一个比较耗时的操作,比如从网站下载XML 文件并呈现到ListView上面的东西吧。
package com.dhanzhang;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class AsyncTaskDemo extends Activity {
private TextView mTextView,Text2;
private Button mStartTask ;
private ListView lv ;
private readData rd;
static SimpleDateFormat sf = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss.SSS");
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.async);
setupViews();
}
public void setupViews() {
mTextView = (TextView) findViewById(R.id.text);
Text2=(TextView)findViewById(R.id.text2) ;
mStartTask=(Button)findViewById(R.id.startTask) ;
lv =(ListView) findViewById( R.id.contentListView ) ;
mStartTask.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if( rd ==null){
rd=new readData();
mTextView.setText(
"BegTime:"+
sf.format(new Date(System.currentTimeMillis()))
);
rd.execute(new Integer[]{
1, 1,100
}) ;
}
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
if( rd !=null){
rd.cancel(true) ;
rd=null;
}
}
private class readData extends AsyncTask<Integer ,Integer, List<String>>{
int seed =0;
int step=0;
int cnt=100;
@Override
protected List<String> doInBackground(Integer... params) {
seed=params[0] ;
step=params[1] ;
cnt =params[2] ;
List<String> msg =new ArrayList<String>(cnt) ;
while ( cnt > 0){
Date d = new Date(System.currentTimeMillis());
seed += step;
String txt= String.format("%d:%d:%s", cnt , seed,sf.format(d));
msg.add(txt);
cnt +=-1 ;
}
return msg ;
}
//执行完成后传送结果给UI线程 此方法最后执行
protected void onPostExecute(List<String> msg) {
lv.setAdapter(new ArrayAdapter<String>(
AsyncTaskDemo.this,
android.R.layout.simple_list_item_1 ,
msg));
Text2.setText(
"EndTime:"+
sf.format(new Date(System.currentTimeMillis()))
);
}
}
}
======================2个记录时间的=======================
AsynaTask 的第一个泛型参数类型是对应 doInBackground()的参数类型 。第三个泛型参数类型是对应的返回类型。第二个是干嘛的,有人知道么。
SDK 版本是:Android 2.2
边做边学的方法。
多线程更新UI的方法
layout 的布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:id="@+id/text2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/startservice"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="startThread1"
/>
<Button
android:id="@+id/stopservice"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="stopThread1"
/>
<Button
android:id="@+id/bindservice"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="startThread2"
/>
<Button
android:id="@+id/unbindservice"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="stopThread2"
/>
<Button
android:id="@+id/over"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="over"
/>
</LinearLayout>
======================2个textView 一个用来显示时间,一个计数==========================
代码如下:
package com.dhanzhang;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class TestHandler extends Activity implements OnClickListener {
private TextView mTextView;
private TextView mTextView2;
private Button startServiceButton;
private Button stopServiceButton;
private Button bindServiceButton;
private Button unbindServiceButton;
private Button over;
protected static final int GUIUPDATEIDENTIFIER = 0x101;
int i = 0;
Thread myRefreshThread = null;
Handler handler2 = new Handler();
// 1.定义一个Handler(一般更新View)
Handler myHandler = new Handler() {
// 2.重写消息处理函数
public void handleMessage(Message msg) {
switch (msg.what) {
// 判断发送的消息
case TestHandler.GUIUPDATEIDENTIFIER:
// 更新View
Date d = new Date(System.currentTimeMillis());
SimpleDateFormat sf = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss.SSS");
mTextView.setText(String.format("Runnable:%s ", sf.format(d)));
break;
}
super.handleMessage(msg);
}
};
Runnable runnable = new Runnable() {
@Override
public void run() {
mTextView2.setText(String.valueOf(i++));
handler2.postDelayed(runnable, 1000);
}
};
class myThread implements Runnable {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
// 3.发送消息
Message message = new Message();
// 发送消息与处理函数里一致
message.what = TestHandler.GUIUPDATEIDENTIFIER;
// 内部类调用外部类的变量
TestHandler.this.myHandler.sendMessage(message);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
setupViews();
}
public void setupViews() {
mTextView = (TextView) findViewById(R.id.text);
mTextView2 = (TextView) findViewById(R.id.text2);
mTextView.setText("Begin To");
mTextView2.setText("Y");
startServiceButton = (Button) findViewById(R.id.startservice);
stopServiceButton = (Button) findViewById(R.id.stopservice);
bindServiceButton = (Button) findViewById(R.id.bindservice);
unbindServiceButton = (Button) findViewById(R.id.unbindservice);
over = (Button) findViewById(R.id.over);
startServiceButton.setOnClickListener(this);
stopServiceButton.setOnClickListener(this);
bindServiceButton.setOnClickListener(this);
unbindServiceButton.setOnClickListener(this);
over.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setResult(Activity.RESULT_OK);
finish();
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
if (myRefreshThread != null) {
myRefreshThread.interrupt();
myRefreshThread.stop();
}
handler2.removeCallbacks(runnable) ;
}
public void onClick(View v) {
if (v == startServiceButton) {
myRefreshThread = new Thread(new myThread());
myRefreshThread.start();
} else if (v == stopServiceButton) {
myRefreshThread.interrupt();
} else if (v == bindServiceButton) {
handler2.post(runnable);
} else if( v== unbindServiceButton) {
handler2.removeCallbacks(runnable) ;
}
}
}
====================PS:===============
onDestroy()的重写可能有问题,不过在虚拟机里看不出来啥问题,不知道实际情况会如何。
Android 版本是2.2
Runnable 接口并非真正的开启了线程(具体的请参见: http://www.cnblogs.com/ghj1976/archive/2011/05/06/2038516.html 这篇文章)
[XmlRoot(ElementName = "item")]
public class MneProductSourceImage
{
[XmlElement(ElementName = "productid")]
public int productid { get; set; }
[XmlIgnore]
public Date imagetime { get; set; }
[XmlElement(ElementName = "imagetime")]
public String ProxyImageTime
{
get
{
return imagetime.ToString("yyyy-MM-dd HH:mm:ss");
}
set
{
imagetime = Date.Parse(value);
}
}
[XmlIgnore ]
public Date istoptime { get; set; }
[XmlElement(ElementName = "istoptime")]
public String ProxyIstoptime
{
get
{
return istoptime.ToString("yyyy-MM-dd HH:mm:ss");
}
set
{
istoptime = Date.Parse(value);
}
}
[XmlElement(ElementName = "width")]
public int width { get; set; }
[XmlElement(ElementName = "height")]
public int height { get; set; }
}
留着这里免得忘记了。。。。妈妈的。误删了一个连恢复都恢复不来了。。。
这种定义方式看起来好记一些。。。。
''
@v1 first operator
@v2 second operator
return v1 + v2
''
return v1+v2
def sum2(v1:{int,"first operator"} , v2:{int,"second operator"}=2, *args ) ->{int, "v1 + v2 "}:
''
this is user to test fo sum2
''
if args ==():
print("No ExtraArgs")
print(args)
return v1+ v2
print( sum()) >> 4
print( sum(1)) >>3
这2 个定义函数的方式都可以啊。
