編輯:中級開發
/**
* 圖片上傳線程
* 將上傳結果通過Handler傳遞給主線程
* @author peter
*/
class MyThread extends Thread implements Runnable {
private String upMsg = "",file="",fileName="";
/**
* 判斷網絡是否可用
*/
public int getCon(String url) {
int con1 = 0;
URL objURL = null;
try {
objURL = new URL(url);
con1 = 1;
} catch (MalformedURLException e2) {
con1 = 0;
}
if (objURL != null) {
URLConnection conn = null;
try {
conn = objURL.openConnection();
conn.setConnectTimeout(1000);
conn.setReadTimeout(1000);
con1 = 1;
} catch (IOException e) {
con1 = 0;
}
if (conn != null) {
try {
conn.connect();
con1 = 1;
} catch (IOException e) {
con1 = 0;
}
}
}
return con1;
}
/**
* 取得請求返回的數據字符串
* @param url
* @return
*/
public String getText(String url){
String text = "";
try {
URL objURL = new URL(url);
URLConnection conn = objURL.openConnection();
conn.setConnectTimeout(6 * 1000);
conn.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
if (br == null) {
return null;
}
while ((inputLine = br.readLine()) != null) {
text += inputLine;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return text;
}
/**
* 圖片上傳
*/
public void uploadFile(){
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
FTPClIEnt ftp = new FTPClIEnt();
String server = "xx.xx.xx.xx";
String username = tm.getDeviceId();
String passWord = "micromulti";
try {
FTP.setDefaultTimeout(30000);
FTP.setDefaultPort(21);
FTP.connect(server);
int reply = FTP.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
FTP.disconnect();
upMsg = "FTP 連接失敗";
} else {
if (FTP.login(username, passWord)) {
FTP.enterLocalPassiveMode();
ftp.setFileType(FTP.BINARY_FILE_TYPE);
FTP.setRemoteVerificationEnabled(false);
FileInputStream fis = new FileInputStream(new File(file));
FTP.storeFile(fileName, fis);
fis.close();
}
FTP.logout();
upMsg = "文件上傳成功";
}
} catch (Exception e) {
upMsg = ""+e;
} finally {
if (FTP.isConnected()) {
try {
FTP.disconnect();
} catch (Exception ioe) {
upMsg = ""+ioe;
}
}
}
}
public void run() {
String file = preBundle.getString("prePath");
String arrs[] = file.split("/");
String fileName = arrs[arrs.length-1];
String fileStrArr[] = fileName.split("-");
String phoneIMSI = fileStrArr[0];
String lat = fileStrArr[1];
String lng = fileStrArr[2];
String shootTime = fileStrArr[3];
// Log.d("lat&lng","*******************lat is:"+lat+" lng is:"+lng+" fileName is:"+fileName);
EditText picInfo = (EditText)findVIEwById(R.id.photoInfo);
String freshUrl ="http://xx.xx.xx.xx:8080/DataAcquisition/photoUploadAction.do?photoWebModel.actiontype=upload";
String postUrl = freshUrl+"&photoWebModel.phoneIMSI="+phoneIMSI
+"&photoWebModel.lat="+lat
+"&photoWebModel.lng="+lng
+"&photoWebModel.shootTime="+shootTime
+"&photoWebModel.picInfo="+picInfo.getText()
+"&photoWebModel.filename="+fileName;
Message message = new Message();
String result = "";
if(this.getCon(postUrl)==1){
result = getText(postUrl);
Log.d("uploadConfirmResult", ">>>>>>>>>>>>>>>>>>"+result.trim());
}else{
message.what = 2;
}
if(result.trim().equals("true")){
String thumbnailFilePath = "sdcard/fatalityUpload/Thumbnail_fatality/"+fileName;
uploadFile(); //執行圖片上傳
Log.d("uploadFile",">>>>>>>>>>>>>>>>>>>>>>>>>complate!stop Upload...");
File file2 = new File(file);
file2.delete();
file2 = null;
File file3 = new File(thumbnailFilePath);
file3.delete();
file3 = null;
Bundle bundle = new Bundle();
bundle.putString("uploadMsg", upMsg);
message.setData(bundle);
message.what = 1;
}else if (result.trim().equals("false1")){
message.what = 3;
}else{}
Log.d("mess.what", "<<<<<<<<<<<<<<<<<<message.what is :"+message.what);
subHandler.sendMessage(message);
}
}
}
預覽還沒有上傳的圖片界面(photovIEw.XML):
本界面實現一個煎蛋的圖像回廊,點擊對應的圖片後即跳轉到圖片編輯上傳界面。
vIEw plaincopy to clipboardprint?
01.<?XML version="1.0" encoding="utf-8"?>
02.<RelativeLayout
03.XMLns:android="http://schemas.android.com/apk/res/android"
04.android:layout_width="fill_parent"
05.android:layout_height="fill_parent">
06.<ImageSwitcher
07.android:id="@+id/switcher"
08.android:layout_width="fill_parent"
09.android:layout_height="fill_parent"
10.android:layout_alignParentTop="true"
11.android:layout_alignParentLeft="true"
12./>
13.<Gallery
14.android:id="@+id/gallery"
15.android:layout_width="fill_parent"
16.android:layout_height="wrap_content"
17.android:layout_alignParentBottom="true"
18.android:layout_alignParentLeft="true"
19./>
20.<!--
21.android:spacing="3dp"
22.-->
23.<Button
24.android:id="@+id/existUpload"
25.android:layout_width="wrap_content"
26.android:layout_height="wrap_content"
27.android:drawableLeft="@drawable/ic_menu_upload_mini"
28.android:layout_marginLeft="380px"
29.android:layout_marginTop="50px"
30.android:text="上傳"
31./>
32.<Button
33.android:id="@+id/backMain"
34.android:layout_width="wrap_content"
35.android:layout_height="wrap_content"
36.android:drawableLeft="@drawable/ic_menu_revert_mini"
37.android:layout_marginLeft="380px"
38.android:text="返回"
39./>
40.</RelativeLayout>
<?XML version="1.0" encoding="utf-8"?>
<RelativeLayout
XMLns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageSwitcher
android:id="@+id/switcher"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
/>
<Gallery
android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
/>
<!--
android:spacing="3dp"
-->
<Button
android:id="@+id/existUpload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/ic_menu_upload_mini"
android:layout_marginLeft="380px"
android:layout_marginTop="50px"
android:text="上傳"
/>
<Button
android:id="@+id/backMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/ic_menu_revert_mini"
android:layout_marginLeft="380px"
android:text="返回"
/>
</RelativeLayout>
代碼部分(PhotoVIEw.Java):
vIEw plaincopy to clipboardprint?
01.package com.bjwmt.camera;
02.import Java.io.File;
03.import Java.util.ArrayList;
04.import Java.util.List;
05.import android.app.Activity;
06.import android.content.Intent;
07.import android.content.pm.ActivityInfo;
08.import android.graphics.Bitmap;
09.import android.graphics.BitmapFactory;
10.import android.graphics.drawable.BitmapDrawable;
11.import android.os.Bundle;
12.import android.view.VIEw;
13.import android.vIEw.WindowManager;
14.import android.view.VIEw.OnClickListener;
15.import android.vIEw.animation.AnimationUtils;
16.import android.widget.AdapterVIEw;
17.import android.widget.Button;
18.import android.widget.Gallery;
19.import android.widget.ImageSwitcher;
20.import android.widget.ImageVIEw;
21.import android.widget.VIEwSwitcher;
22.import android.widget.AdapterVIEw.OnItemClickListener;
23.import android.widget.Gallery.LayoutParams;
24./**
25. * 圖片藝廊式的選擇界面 實現
26. * 顯示照片(AdapterView)、等待聽取照片單機動作(OnItemSelectedListener)、進行照片切換動作(ViewSwitcher)、負責保存照片(VIEwFactory)等功能
27. */
28.public class PhotoVIEw extends Activity implements
29.AdapterView.OnItemSelectedListener, ViewSwitcher.VIEwFactory {
30.private static ImageSwitcher mSwitcher;
31.private static Button returnButton;
32.private static Button saveButton;
33.private List<String> phoList;
34.// private List<String> or_phoList;
35.private String newFilePath = "";
36.@SuppressWarnings("unchecked")
37.private static List<String> readFiles(String path) {
38.List picFiles = new ArrayList();
39.// 構建文件對象
40.File dir = new File(path);
41.// 得到改文件夾下所有文件
42.File[] files = dir.listFiles();
43.if (files != null) {
44.for (int i = 0; i < files.length; i++) {
45.String fileName = files[i].getName();
46.// 過濾所有後綴為.jpg的文件
47.if (fileName.lastIndexOf(".") > 0
48.&& fileName.substring(fileName.lastIndexOf(".") + 1,
49.fileName.length()).equals("jpg")||fileName.substring(fileName.lastIndexOf(".") + 1,
50.fileName.length()).equals(".gif")) {
51.picFiles.add(files[i].getPath());
52.}
53.}
54.}
55.return picFiles;
56.}
57.// Thread myT = new Thread(new Runnable() {
58.// public void run() {
59.// // TODO 讓該線程實現的功能
60.// try {
61.// or_phoList = readFiles("sdcard/fatalityUpload/");
62.// } catch (Exception e) {
63.// e.printStackTrace();
64.// }
65.// }
66.// });
67.public static void setInSampleSize(BitmapFactory.Options options,int targetSize) {
68.options.outWidth >>= 1;
69.options.outHeight >>= 1;
70.while (options.outWidth > targetSize || options.outHeight > targetSize) {
71.options.inSampleSize <<= 1;
72.options.outWidth >>= 1;
73.options.outHeight >>= 1;
74.}
75.}
76.@Override
77.public void onCreate(Bundle savedInstanceState) {
78.super.onCreate(savedInstanceState);
79.setContentView(R.layout.photovIEw);
80.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); // 橫屏
81.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
82.WindowManager.LayoutParams.FLAG_FULLSCREEN);// 全屏
83.this.setListener();
84.mSwitcher = (ImageSwitcher) findVIEwById(R.id.switcher);
85.mSwitcher.setFactory(this);
86.// mSwitcher.setOnClickListener(clickImageVIEw);
87.// 設置照片切換時的淡入淡出模式
88.mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
89.android.R.anim.fade_in));
90.mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
91.android.R.anim.fade_out));
92.Gallery g = (Gallery) findVIEwById(R.id.gallery);
93.g.setAdapter(new ImageAdapter(this,phoList));
94.g.setOnItemSelectedListener(this);
95.g.setOnItemClickListener(new OnItemClickListener()
96. {
97. public void onItemClick(AdapterVIEw<?> parent,
98. VIEw v, int position, long id)
99. {
100. //當內容被點擊的時候處理的事件
101. }
102. });
103.}
104.private void setListener() {
105.phoList = readFiles("sdcard/fatalityUpload/Thumbnail_fatality/");
106.returnButton = (Button) findVIEwById(R.id.backMain);
107.saveButton = (Button) findVIEwById(R.id.existUpload);
108.returnButton.setOnClickListener(returnClick);
109.saveButton.setOnClickListener(saveClick);
110.}
111.private OnClickListener saveClick = new OnClickListener() {
112.public void onClick(VIEw v) {
113.Intent intent = new Intent();
114.Bundle bundle = new Bundle();
115.// bundle.putByteArray("picPre", newData);
116.bundle.putString("picPath",newFilePath);
117.// intent.putExtra("picPre", data);
118.intent.putExtras(bundle);
119.intent.setClass(PhotoVIEw.this, SubmitPhoto.class);
120.finish();
121.startActivity(intent);
122.}
123.};
124.private OnClickListener returnClick = new OnClickListener() {
125.public void onClick(VIEw v) {
126.Intent intent = new Intent();
127.intent.setClass(PhotoVIEw.this, MainPage.class);
128.finish();
129.startActivity(intent);
130.}
131.};
132./**
133.* 當用戶點擊照片藝廊中的照片時觸發該函數
134.*/
135.@SuppressWarnings("unchecked")
136.public void onItemSelected(AdapterView parent, VIEw v, int position, long id) {
137.String fileArr[] = phoList.get(position).toString().split("/");
138.newFilePath = "sdcard/fatalityUpload/fatality/"+fileArr[fileArr.length-1];
139.// Log.d("onItemSelected LOG",">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+phoList.get(position).toString());
140.// Log.d("onItemSelected LOG",">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+newFilePath);
141.Bitmap bm = BitmapFactory.decodeFile(phoList.get(position).toString());
142.BitmapDrawable bmpDraw=new BitmapDrawable(bm);
143.mSwitcher.setImageDrawable(bmpDraw);
144.}
145.public void onNothingSelected(AdapterVIEw<?> arg0) {
146.}
147./**
148.* 顯示照片函數
149.*/
150.public View makeVIEw(){
151.ImageView imageView = new ImageVIEw(this);
152.imageView.setScaleType(ImageVIEw.ScaleType.CENTER_INSIDE);
153.android.widget.FrameLayout.LayoutParams imageSwitcher = new ImageSwitcher.LayoutParams(
154.LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
155.imageVIEw.setLayoutParams(imageSwitcher);
156.return imageVIEw;
157.}
158./**
159.* 當點擊圖片時切換到圖片編輯上傳界面
160.*/
161.// private OnClickListener clickImageVIEw = new OnClickListener() {
162.// public void onClick(VIEw v) {
163.// Intent intent = new Intent();
164.// intent.setClass(PhotoVIEw.this, SubmitPhoto.class);
165.// finish();
166.// startActivity(intent);
167.// }
168.// };
169.}
package com.bjwmt.camera;
import Java.io.File;
import Java.util.ArrayList;
import Java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.VIEw;
import android.vIEw.WindowManager;
import android.view.VIEw.OnClickListener;
import android.vIEw.animation.AnimationUtils;
import android.widget.AdapterVIEw;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageVIEw;
import android.widget.VIEwSwitcher;
import android.widget.AdapterVIEw.OnItemClickListener;
import android.widget.Gallery.LayoutParams;
/**
* 圖片藝廊式的選擇界面 實現
* 顯示照片(AdapterView)、等待聽取照片單機動作(OnItemSelectedListener)、進行照片切換動作(ViewSwitcher)、負責保存照片(VIEwFactory)等功能
*/
public class PhotoVIEw extends Activity implements
AdapterView.OnItemSelectedListener, ViewSwitcher.VIEwFactory {
private static ImageSwitcher mSwitcher;
private static Button returnButton;
private static Button saveButton;
private List<String> phoList;
// private List<String> or_phoList;
private String newFilePath = "";
@SuppressWarnings("unchecked")
private static List<String> readFiles(String path) {
List picFiles = new ArrayList();
// 構建文件對象
File dir = new File(path);
// 得到改文件夾下所有文件
File[] files = dir.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
String fileName = files[i].getName();
// 過濾所有後綴為.jpg的文件
if (fileName.lastIndexOf(".") > 0
&& fileName.substring(fileName.lastIndexOf(".") + 1,
fileName.length()).equals("jpg")||fileName.substring(fileName.lastIndexOf(".") + 1,
fileName.length()).equals(".gif")) {
picFiles.add(files[i].getPath());
}
}
}
return picFiles;
}
// Thread myT = new Thread(new Runnable() {
// public void run() {
// // TODO 讓該線程實現的功能
// try {
// or_phoList = readFiles("sdcard/fatalityUpload/");
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// });
public static void setInSampleSize(BitmapFactory.Options options,int targetSize) {
options.outWidth >>= 1;
options.outHeight >>= 1;
while (options.outWidth > targetSize || options.outHeight > targetSize) {
options.inSampleSize <<= 1;
options.outWidth >>= 1;
options.outHeight >>= 1;
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photovIEw);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); // 橫屏
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);// 全屏
this.setListener();
mSwitcher = (ImageSwitcher) findVIEwById(R.id.switcher);
mSwitcher.setFactory(this);
// mSwitcher.setOnClickListener(clickImageVIEw);
// 設置照片切換時的淡入淡出模式
mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_in));
mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_out));
Gallery g = (Gallery) findVIEwById(R.id.gallery);
g.setAdapter(new ImageAdapter(this,phoList));
g.setOnItemSelectedListener(this);
g.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterVIEw<?> parent,
VIEw v, int position, long id)
{
//當內容被點擊的時候處理的事件
}
});
}
private void setListener() {
phoList = readFiles("sdcard/fatalityUpload/Thumbnail_fatality/");
returnButton = (Button) findVIEwById(R.id.backMain);
saveButton = (Button) findVIEwById(R.id.existUpload);
returnButton.setOnClickListener(returnClick);
saveButton.setOnClickListener(saveClick);
}
private OnClickListener saveClick = new OnClickListener() {
public void onClick(VIEw v) {
Intent intent = new Intent();
Bundle bundle = new Bundle();
// bundle.putByteArray("picPre", newData);
bundle.putString("picPath",newFilePath);
// intent.putExtra("picPre", data);
intent.putExtras(bundle);
intent.setClass(PhotoVIEw.this, SubmitPhoto.class);
finish();
startActivity(intent);
}
};
private OnClickListener returnClick = new OnClickListener() {
public void onClick(VIEw v) {
Intent intent = new Intent();
intent.setClass(PhotoVIEw.this, MainPage.class);
finish();
startActivity(intent);
}
};
/**
* 當用戶點擊照片藝廊中的照片時觸發該函數
*/
@SuppressWarnings("unchecked")
public void onItemSelected(AdapterView parent, VIEw v, int position, long id) {
String fileArr[] = phoList.get(position).toString().split("/");
newFilePath = "sdcard/fatalityUpload/fatality/"+fileArr[fileArr.length-1];
// Log.d("onItemSelected LOG",">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+phoList.get(position).toString());
// Log.d("onItemSelected LOG",">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+newFilePath);
Bitmap bm = BitmapFactory.decodeFile(phoList.get(position).toString());
BitmapDrawable bmpDraw=new BitmapDrawable(bm);
mSwitcher.setImageDrawable(bmpDraw);
}
public void onNothingSelected(AdapterVIEw<?> arg0) {
}
/**
* 顯示照片函數
*/
public View makeVIEw(){
ImageView imageView = new ImageVIEw(this);
imageView.setScaleType(ImageVIEw.ScaleType.CENTER_INSIDE);
android.widget.FrameLayout.LayoutParams imageSwitcher = new ImageSwitcher.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
imageVIEw.setLayoutParams(imageSwitcher);
return imageVIEw;
}
/**
* 當點擊圖片時切換到圖片編輯上傳界面
*/
// private OnClickListener clickImageVIEw = new OnClickListener() {
// public void onClick(VIEw v) {
// Intent intent = new Intent();
// intent.setClass(PhotoVIEw.this, SubmitPhoto.class);
// finish();
// startActivity(intent);
// }
// };
}
幫助類(ImageAdapter.Java):
vIEw plaincopy to clipboardprint?
01.package com.bjwmt.camera;
02.import Java.util.List;
03.import android.content.Context;
04.import android.content.res.TypedArray;
05.import android.graphics.Bitmap;
06.import android.graphics.BitmapFactory;
07.import android.view.VIEw;
08.import android.view.VIEwGroup;
09.import android.widget.BaseAdapter;
10.import android.widget.GridVIEw;
11.import android.widget.ImageVIEw;
12.public class ImageAdapter extends BaseAdapter {
13. int mGalleryItemBackground;
14. private Context mContext;
15. private List<String> lis;
16. public ImageAdapter(Context c,List<String> li)
17. {
18. mContext = c;
19. lis=li;
20. TypedArray a = mContext.obtainStyledAttributes(R.styleable.Gallery);
21. mGalleryItemBackground = a.getResourceId(
22. R.styleable.Gallery_android_galleryItemBackground, 0);
23. a.recycle();
24. }
25. public int getCount()
26. {
27. return lis.size();
28. }
29. public Object getItem(int position)
30. {
31. return position;
32. }
33. public long getItemId(int position)
34. {
35. return position;
36. }
37. public View getView(int position, View convertVIEw,
38. VIEwGroup parent)
39. {
40. ImageView i = new ImageVIEw(mContext);
41. Bitmap bm = BitmapFactory.decodeFile(lis.get(position).toString());
42. i.setImageBitmap(bm);
43. i.setScaleType(ImageVIEw.ScaleType.CENTER_CROP);
44. i.setLayoutParams(new GridVIEw.LayoutParams(88, 88));
45. i.setBackgroundResource(mGalleryItemBackground);
46. i.setPadding(3,3,3,3);
47. return i;
48. }
49.}
本文來自CSDN博客,轉載請標明出處:http://blog.csdn.Net/cfwdl/archive/2010/07/19/5746708.ASPx
簡介: 本文詳細介紹了 Android 應用編程中 Activity 的生命周期、通信方式和 Intent Filter 等內容,並提供了一些日常開發中經常用
在Android 3.0中除了我們重點講解的Fragment外,Action Bar也是一個重要的內容,Action Bar主要是用於代替傳統的標題欄,對於androi
兩位Google開發者演示了Android 3.0——該開源移動操作系統的首個支持平板設備的版本。Android 3.0也被稱為蜂巢(Honeycomb),這也是第一個
在android開發應用中,默認的Button是由系統渲染和管理大小的。而我們看到的成功的移動應用,都是有著酷炫的外觀和使用體驗的。因此,我們在開發產品的時候,需要對默