基于Android的 拍照上传 程序开发

原文地址为: 基于Android的 拍照上传 程序开发

 大家好,我是PETER(cfwdl)。写这篇文章是为了帮助以前没有没有接触过anroid或是刚刚入门并没有摸过手机的硬件设备监测、使用等功能的朋友,给大家一个我自己的写的心得和经验,我也是新手,所以大家互相交换一下经验吧。当然每个程序都会有问题,因为我不是最终用户,软件的测试工作没有好好测试过,大家凑合看看吧~!

 


程序介绍:

本程序主要完成一个煎蛋的android手机拍照程序(本程序的拍照功能比较简单,没有添加处理图像、手机自动对焦等功能,如果有需要的朋友可以自行参考一下相关linstener或action的资料)

主功能: 手机拍照、拍照预览、图片的存储、图片资料编辑、图像上传等功能

其他相关需求:监测手机网络状态、监测手机GPS状态、获取GPS位置、获取基站位置等。

 


需求分析:

(程序流程)

正如上图所示,我大致的画了一下这个程序的简单的工作流程。

那么,各位看官们,现在开始我们的程序开发之旅吧。

 


程序设计:

 

PS:本人不是美工,所以界面肯定灰常粗糙,不过不影响我们展示功能~!大家权且凑合继续看

 

 

主界面(camera_surface.xml):

 

本界面使用AbsoluteLayout布局来设计该界面,

下面的代码中我定义了一个全屏的SurfaceView用来在我们进入程序的第一个界面(就是拍照界面),

一个ID为nowLocality的TextView,来动态的刷新用户手机当前获取到的位置信息。

三个Button 分别是: 拍照、上传、退出 这个大概不用我再啰嗦了。

 

 

<?xml version="1.0" encoding="utf-8"?> <AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal"> <SurfaceView android:id="@+id/surface_camera" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1"> </SurfaceView> <TextView android:id="@+id/nowLocality" android:layout_x="10px" android:layout_y="25px" android:textColor="@color/red" android:textSize="14px" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="正在获取当前位置" /> <Button android:text="拍照" android:layout_x="360px" android:layout_y="20px" android:drawableLeft="@drawable/ic_menu_camera" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/paizhao" /> <Button android:text="上传" android:drawableLeft="@drawable/ic_menu_upload_mini" android:textSize="16px" android:layout_x="360px" android:layout_y="70px" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/uploadPhoto" /> <Button android:text="退出" android:textSize="16px" android:drawableLeft="@drawable/ic_menu_revert_mini" android:layout_x="360px" android:layout_y="120px" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/exitPro" /> </AbsoluteLayout> 

 

对应本界面的程序代码(MainPage.java):

 

程序的相关部分我都已经添加了注释,大概的功能各位应该都可以看明白,流程就是按onCreate()里的顺序执行下来。

 

<textarea cols="50" rows="15" name="code" class="java">package com.bjwmt.camera; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.PixelFormat; import android.hardware.Camera; import android.hardware.Camera.AutoFocusCallback; import android.hardware.Camera.PictureCallback; import android.hardware.Camera.ShutterCallback; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.telephony.TelephonyManager; import android.text.Html; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class MainPage extends Activity implements SurfaceHolder.Callback, OnClickListener { /** * 程序存放的图片路径是在/sdcard/fatalityUpload这个文件夹 */ private SurfaceView mSurfaceView; private Camera mCamera; private SurfaceHolder mSurfaceHolder; private boolean mPreviewRunning; private TextView nowLocality; private Button exitButton; private Button uploadButton; private Button paizhaoButton; // 实例化一个TelephonyManager 创建android的电话管理 private TelephonyManager tm; private Date today; private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss"); private String fileName; private String lat = "", lng = "";// 经度和纬度 private String latLongString; private GpsThread gpsThread; private DBHelper dbHelper; private Cursor cursor; /** * 本界面的主函数 */ @Override public void onCreate(Bundle savedInstanceState) { checkMysoftStage(); super.onCreate(savedInstanceState); setContentView(R.layout.camera_surface); // 摄像头界面将通过全屏显示,没有"标题(title)"; getWindow().setFormat(PixelFormat.TRANSLUCENT); // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, // WindowManager.LayoutParams.FLAG_FULLSCREEN);// 全屏 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);// 横屏 this.initMyCamera(); } /** * 检查一下手机设备各项硬件的开启状态 */ public void checkMysoftStage(){ /* * 先看手机是否已插入sd卡 然后判断sd卡里是不是已经创建了fatalityUpload文件夹用来存储本程序拍下来的照片 * 如果没有创建的话就重新在sdcard里创建fatalityUpload文件夹 */ if (existSDcard()) { //判断手机SD卡是否存在 if (new File("/sdcard").canRead()) { File file = new File("sdcard/fatalityUpload"); if (!file.exists()) { file.mkdir(); file = new File("sdcard/fatalityUpload/Thumbnail_fatality"); file.mkdir(); file = new File("sdcard/fatalityUpload/fatality"); file.mkdir(); } } } else { new AlertDialog.Builder(this).setMessage("检查到没有存储卡,请插入手机存储卡再开启本应用") .setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialoginterface, int i) { finish(); } }).show(); } /* * 此处开始初始化数据库 try { dbHelper = new DBHelper(this); dbHelper.open(this); cursor = dbHelper.loadAll(); if(!(cursor!=null &amp;&amp; cursor.getCount()&gt;0)){ dbHelper.initData(); } cursor.close(); dbHelper.close(); } catch (Exception e) { Log.d("save data", "save data fail"); } finally { this.dbHelper.close(); } */ ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo networkinfo = connectivityManager.getActiveNetworkInfo(); if (networkinfo == null || !networkinfo.isAvailable()) { // 当前网络不可用 new AlertDialog.Builder(MainPage.this) .setMessage("检查到没有可用的网络连接,请打开网络连接") .setPositiveButton("确定", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialoginterface, int i){ ComponentName cn = new ComponentName("com.android.settings","com.android.settings.Settings"); Intent intent = new Intent(); intent.setComponent(cn); intent.setAction("android.intent.action.VIEW"); startActivity(intent); // finish(); } } ).show(); } } /** * 初始化组件 */ public void initMyCamera() { setListensers(); // TelephonyManager是android的电源通讯的帮助类,通过实例化TelephonyManager来实现操作类似获取本机 // IME码,手机号等信息 tm = (TelephonyManager) this .getSystemService(Context.TELEPHONY_SERVICE); // 初始化拍摄模块 mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera); // mSurfaceView.setOnClickListener(this); mSurfaceHolder = mSurfaceView.getHolder(); mSurfaceHolder.addCallback(MainPage.this); mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); gpsThread = new GpsThread(); gpsThread.start(); // 设置监听器,自动更新的最小时间为间隔1秒,最小位移变化超过3米 // mLocationManager.requestLocationUpdates(provider, 1000, 3, // locationListener); } /** * 此函数负责两个工作 1.实例化屏幕上的按钮 2.为按钮添加Listener */ private void setListensers() { nowLocality = (TextView) findViewById(R.id.nowLocality); exitButton = (Button) findViewById(R.id.exitPro); uploadButton = (Button) findViewById(R.id.uploadPhoto); paizhaoButton = (Button) findViewById(R.id.paizhao); exitButton.setOnClickListener(clickExitButton); uploadButton.setOnClickListener(clickUploadButton); paizhaoButton.setOnClickListener(clickShootButton); } /** * 当预览界面的格式和大小发生改变时,该方法被调用 */ public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { if (mPreviewRunning) { mCamera.stopPreview(); } Camera.Parameters p = mCamera.getParameters(); p.setPreviewSize(w, h); mCamera.setParameters(p); try { mCamera.setPreviewDisplay(holder); } catch (IOException e) { e.printStackTrace(); } mCamera.startPreview(); mPreviewRunning = true; } /** * 重点函数 此处实例化了本界面的PictureCallback * 当用户拍完一张照片的时候触发onPictureTaken,这时候对拍下的照片进行相应的处理操作 */ PictureCallback mPictureCallback = new PictureCallback() { public void onPictureTaken(byte[] data, Camera camera) { if (data != null) { try { today = new Date(); // 定义fileName 用来设定拍照后的文件名 // 结构: IMSI号 + 经度+ &amp; + 纬度+ 格式化后的当前时间 (本来结构应该是 手机号 + 精度&amp;纬度 + 格式化后的当前时间)但是因为手机号有获取不到的情况,所以换为了IMSI号 fileName = tm.getDeviceId() + "-" + lat + "-" + lng + "-" + sdf.format(today); //tm.getLine1Number()获取手机号,这里直接是获取不到的,需要运营商的API解析 Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length); BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(String.format( "sdcard/fatalityUpload/fatality/" + fileName + ".jpg", System .currentTimeMillis()))); bm.compress(Bitmap.CompressFormat.JPEG, 60, bos); bos.flush(); bos.close(); BufferedOutputStream bos1 = new BufferedOutputStream( new FileOutputStream(String.format( "sdcard/fatalityUpload/Thumbnail_fatality/" + fileName + ".jpg", System .currentTimeMillis()))); Bitmap bm1 = Bitmap.createScaledBitmap(bm, 100, 100, false); bm1.compress(Bitmap.CompressFormat.JPEG, 100, bos1); bos1.flush(); bos1.close(); removeDialog(0); // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // bm.compress(Bitmap.CompressFormat.PNG, 30, baos); // byte[] newData = baos.toByteArray(); // 然后传递图片信息到 图像预览界面 Intent intent = new Intent(); Bundle bundle = new Bundle(); // bundle.putByteArray("picPre", newData); bundle.putString("picPath", "/sdcard/fatalityUpload/fatality/" + fileName + ".jpg"); // intent.putExtra("picPre", data); intent.putExtras(bundle); intent.setClass(MainPage.this, PhotoPreview.class); // if (mLocationManager != null) { // mLocationManager.removeUpdates(locationListener); // } if(!gpsThread.isInterrupted()){ gpsThread.stopGspListener(); gpsThread.interrupt(); } finish(); startActivity(intent); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } }; /** * 创建Camera对象函数 初次实例化,界面打开时该方法自动调用 */ public void surfaceCreated(SurfaceHolder holder) { // Thread openCameraThread = new Thread( // new Runnable() { // public void run() { // mCamera = Camera.open(); // } // } // ).start(); mCamera = Camera.open();// &ldquo;打开&rdquo;摄像头 } /** * 当用户进行 点击 操作的时候触发此事件,不过貌似没有起作用,有待测试 */ public void onClick(View v) { mCamera.takePicture(mShutterCallback, null, mPictureCallback); } /** * 在相机快门关闭时候的回调接口,通过这个接口来通知用户快门关闭的事件, * 普通相机在快门关闭的时候都会发出响声,根据需要可以在该回调接口中定义各种动作, 例如:使设备震动 */ ShutterCallback mShutterCallback = new ShutterCallback() { public void onShutter() { // just log ,do nothing Log.d("ShutterCallback", "...onShutter..."); } }; // PictureCallback rowCallback = new PictureCallback(){ // public void onPictureTaken(byte[] data, Camera camera) { // // } // }; /** * 销毁函数 当预览界面被关闭时,该方法被调用 */ public void surfaceDestroyed(SurfaceHolder holder) { mCamera.stopPreview(); mPreviewRunning = false; mCamera.release(); mCamera = null; } /* * 点击屏幕上的"退出"键时触发该Listener监听此按钮的动作 */ private OnClickListener clickExitButton = new OnClickListener() { public void onClick(View v) { new AlertDialog.Builder(MainPage.this).setTitle("提示").setMessage( "确定退出?").setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // if (mLocationManager != null) { // mLocationManager // .removeUpdates(locationListener); // } if(!gpsThread.isInterrupted()){ gpsThread.stopGspListener(); gpsThread.interrupt(); } finish(); } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // 取消按钮事件 } }).show(); } }; /* * 点击屏幕上的"上传"键时触发该Listener监听此按钮的动作 */ private OnClickListener clickUploadButton = new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(); intent.setClass(MainPage.this, PictrueView.class);// PhotoView // if (mLocationManager != null) { // mLocationManager.removeUpdates(locationListener); // } if(!gpsThread.isInterrupted()){ gpsThread.stopGspListener(); gpsThread.interrupt(); } finish(); startActivity(intent); } }; /* * 点击屏幕上的"拍照"键时触发该Listener监听此按钮的动作 */ private OnClickListener clickShootButton = new OnClickListener() { public void onClick(View v) { showDialog(0); mCamera.takePicture(mShutterCallback, null, mPictureCallback); } }; // 声明三个menu键带出来的按钮 public static final int ITEM_1_ID = Menu.FIRST; public static final int ITEM_2_ID = Menu.FIRST + 1; public static final int ITEM_3_ID = Menu.FIRST + 2; // 初始化Menu菜单,用户按下menu键时自动触发 public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, ITEM_1_ID, 0, "设置"); menu.add(0, ITEM_2_ID, 1, "关于"); menu.add(0, ITEM_3_ID, 2, "退出"); return true; } /** * 处理用户按下menu键时的操作 */ public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case 1: // 调出系统设置界面 ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.Settings"); Intent intent = new Intent(); intent.setComponent(cn); intent.setAction("android.intent.action.VIEW"); startActivity(intent); return true; case 2: // 关于 showDialog(1); return true; case 3: // 退出 new AlertDialog.Builder(this).setTitle("提示").setMessage("确定退出?") .setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { setResult(RESULT_OK);// 确定按钮事件 // if (mLocationManager != null) { // mLocationManager // .removeUpdates(locationListener); // } if(!gpsThread.isInterrupted()){ gpsThread.stopGspListener(); gpsThread.interrupt(); } finish(); } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // 取消按钮事件 } }).show(); return true; } return false; } /** * 当用户按下手机实体按键时触发 如果按下的是拍照键的话返回一个true,其他都是false */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_CAMERA) { return super.onKeyDown(keyCode, event); } else return false; } /** * 判断存储卡是否存在 * * @return */ public boolean existSDcard() { if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { return true; } else return false; } /** * 相机自动对焦函数 */ AutoFocusCallback autoFocusCallback = new AutoFocusCallback() { public void onAutoFocus(boolean success, Camera camera) { } }; @Override protected Dialog onCreateDialog(int id) { switch (id) { case 1: { return new AlertDialog.Builder(MainPage.this) .setIcon(R.drawable.ic_menu_info_details) .setTitle("关于拍照上传软件") .setMessage( Html.fromHtml("&lt;font color=#E43E07 &gt;程序功能介绍:&lt;/font&gt;&lt;p&gt;本程序用于图片拍摄及上传图片等功能&lt;/p&gt;" + "&lt;font color=#E43E07 &gt;注意:&lt;/font&gt;&lt;p&gt;使用本程序前,请先开启用户手机的GPS及无线网络。(拍照界面中点击 menu键-&gt;设置-&gt;安全与位置/无限网络 开启GPS及无限网络)&lt;/p&gt;" + "&lt;p align=center color=#767676 size=12px&gt;PETER制作 版权所有&lt;/p&gt;")) .setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { removeDialog(1); } }).create(); } case 0: { ProgressDialog dialog = new ProgressDialog(this); dialog.setMessage("处理中,请稍后..."); dialog.setIndeterminate(true); dialog.setCancelable(true); return dialog; } } return null; } Handler myHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 0: Bundle bundle = msg.getData(); // Log.d("Thread Test", "&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;handler get message"+msg.what); lat = bundle.getString("lat"); lng = bundle.getString("lng"); latLongString = bundle.getString("latLongString"); // Log.d("handler Text", "&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;"+latLongString+" lat:"+lat+" lng:"+lng); nowLocality.setText(System.currentTimeMillis() + ":/n" + latLongString); break; case 1: AlertDialog dialog1 = new AlertDialog.Builder(MainPage.this) .setTitle("提示").setMessage( "检测到GPS/A-GPS没有开启 /n 点击 确定 进入系统设置,点击 取消 结束").setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* * 转到设置界面 */ Intent fireAlarm = new Intent( "android.settings.LOCATION_SOURCE_SETTINGS"); fireAlarm .addCategory(Intent.CATEGORY_DEFAULT); startActivity(fireAlarm); } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if(!gpsThread.isInterrupted()){ gpsThread.stopGspListener(); gpsThread.interrupt(); } finish(); } }).create(); dialog1.show(); break; case 2: AlertDialog dialog2 = new AlertDialog.Builder(MainPage.this) .setTitle("提示").setMessage("无法获得当前位置,稍后将会重试") .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // finish(); } }).create(); dialog2.show(); break; } super.handleMessage(msg); } }; /** * 手机的GPS线程 * @author peter */ class GpsThread extends Thread implements Runnable { private Looper mLooper; private LocationManager mLocationManager; private Location location; private Message message; private long preTime; String latLongStr = "",latitude = "",longitude = ""; public Looper getLooper() { return mLooper; } public void quit() { mLooper.quit(); } private void updateWithNewLocation(Location slocation) { if (slocation != null) { latitude = Double.toString(slocation.getLatitude()); longitude = Double.toString(slocation.getLongitude()); long subTime = (System.currentTimeMillis() - preTime) / 1000; float v = (subTime == 0 || location == null) ? 0 : (location .distanceTo(slocation) / subTime); latLongStr = "纬度:" + latitude + "/n经度:" + longitude + "/n速度:" + v + " m/s , " + v * 3.6 + " km/h"; location = slocation; preTime = System.currentTimeMillis(); } else { latLongStr = "无法获取地理信息"; } } private LocationListener locationListener = new LocationListener() { // 底层获得的位置会通过这个接口上报给应用 public void onLocationChanged(Location location) { message.what = 0; updateWithNewLocation(location); // Log.d("Thread Test", "*************************GPS IS OPEN!"); } // Provider被disable时触发此函数,比如GPS被关闭 public void onProviderDisabled(String provider) { message.what = 1; // Log.d("Thread Test", "*************************GPS IS CLOSED!"); } // Provider被enable时触发此函数,比如GPS被打开 public void onProviderEnabled(String provider) { } /* * 位置服务状态的变化通过这个接口上报 * Provider的转态在可用、暂时不可用和无服务三个状态直接切换时触发此函数 */ public void onStatusChanged(String provider, int status, Bundle extras) { message.what = 2; } }; @SuppressWarnings("static-access") public void run(){ Looper.prepare(); mLooper = Looper.myLooper(); // 此处实例化了 手机的本地位置服务 的一个对象 mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE);// 设置为最大精度 criteria.setAltitudeRequired(false);// 不要求海拔信息 criteria.setBearingRequired(false);// 不要求方位信息 criteria.setCostAllowed(true);// 是否允许付费 criteria.setPowerRequirement(Criteria.POWER_LOW);// 对电量的要求 String provider = mLocationManager.getBestProvider(criteria, true); while (!Thread.currentThread().isInterrupted()) { mLocationManager.requestLocationUpdates(provider, 1000, 1, locationListener); location = mLocationManager.getLastKnownLocation(provider); // updateWithNewLocation(location); // 更新位置 while(location == null){ preTime = System.currentTimeMillis(); //刷新Provider信息 mLocationManager.requestLocationUpdates(provider, 1000, 1, locationListener); //获得最新的位置数据 location = mLocationManager.getLastKnownLocation(provider); updateWithNewLocation(location); // 更新位置 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } try { message = new Message(); updateWithNewLocation(location); // 更新位置 Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } // Log.d("Thread Test", "*************************Message.what's Value is:"+message.what); Bundle data = new Bundle(); data.putString("latLongString", latLongStr); data.putString("lat", latitude); data.putString("lng", longitude); message.setData(data); myHandler.sendMessage(message); } Looper.loop(); } public void stopGspListener(){ if(mLocationManager!=null){ mLocationManager.removeUpdates(locationListener); } } }; }</textarea> 

 

 

图像预览界面(photo_preview.xml):

 

当用户在主界面点击“拍照”后进入本界面,界面内容

一个ImageView展示刚刚用户拍下来的照片,

两个button “保存”和“放弃”

 

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TableLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:stretchColumns="*" android:background="@color/white" > <TableRow > <ImageView android:id="@+id/previewPic" android:layout_width="wrap_content" android:layout_height="235px" /> <!-- android:src="@drawable/javamylife" --> </TableRow> <TableRow> <TableLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:stretchColumns="*" android:background="@color/white" > <TableRow> <Button android:id="@+id/returnShoot" android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawableLeft="@drawable/ic_menu_revert_mini" android:gravity="center" android:text="放弃" /> <Button android:id="@+id/savePicture" android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawableLeft="@drawable/ic_menu_save" android:gravity="center" android:text="保存" /> </TableRow> </TableLayout> </TableRow> </TableLayout> </LinearLayout> 

 

程序代码(PictrueView.java):

 

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.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import android.widget.AdapterView.OnItemClickListener; public class PictrueView extends Activity{ private List<String> phoList; private static ImageAdapter myImageAdapter; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.picture_view); phoList = readFiles("sdcard/fatalityUpload/Thumbnail_fatality/"); GridView gridview=(GridView)findViewById(R.id.picGridView);//找到main.xml中定义gridview 的id myImageAdapter = new ImageAdapter(this,phoList); gridview.setAdapter(myImageAdapter);//调用ImageAdapter.java gridview.setOnItemClickListener(new OnItemClickListener(){//监听事件 public void onItemClick(AdapterView<?> parent, View view, int position, long id){ // myImageAdapter.getItemId(position); String fileArr[] = phoList.get(position).toString().split("/"); String newFilePath = "sdcard/fatalityUpload/fatality/"+fileArr[fileArr.length-1]; Intent intent = new Intent(); Bundle extras = new Bundle(); extras.putString("prePath", newFilePath); intent.putExtras(extras); intent.setClass(PictrueView.this,SubmitPhoto.class); finish(); startActivity(intent); // Toast.makeText(PictrueView.this, ""+position,Toast.LENGTH_SHORT).show();//显示信息; } }); } @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")) { picFiles.add(files[i].getPath()); } } } return picFiles; } }  

图像内容编辑上传界面:

 

<?xml version="1.0" encoding="UTF-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:scrollbars="none"> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" > <TableLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:stretchColumns="*" > <TableRow> <Spinner android:id="@+id/stationId" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </TableRow> <TableRow> <EditText android:id="@+id/photoInfo" android:layout_width="fill_parent" android:layout_height="wrap_content" android:lines="3" android:singleLine="true" android:text="图片信息" /> </TableRow> <TableRow> <ImageView android:id="@+id/subPicImgView" android:adjustViewBounds="true" android:layout_width="wrap_content" android:layout_height="300px" /> </TableRow> <TableRow> <TableLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:stretchColumns="*" > <TableRow> <Button android:id="@+id/subButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawableLeft="@drawable/ic_menu_upload_mini" android:text="上传" /> <Button android:id="@+id/returnMain" android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawableLeft="@drawable/ic_menu_revert_mini" android:text="返回" /> </TableRow> </TableLayout> </TableRow> </TableLayout> </LinearLayout> </ScrollView> 

 

代码部分(SubmitPhoto.java):

 

package com.bjwmt.camera; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.telephony.TelephonyManager; import android.text.Html; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Spinner; public class SubmitPhoto extends Activity{ private Button subButton; private Button returnButton; private ImageView subPicImgView; private Bundle preBundle; private MyThread myThread; // private Spinner stationSpinner; private DBHelper helper; private Cursor cursor; private List<StationModel> list = new ArrayList<StationModel>(); // private MyThread thread = new MyThread(); @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.photo_submit); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); //横屏 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);//全屏 setListener(); Bitmap bitmap = getBitMap(); BitmapDrawable bmpDraw=new BitmapDrawable(bitmap); subPicImgView.setImageDrawable(bmpDraw); bitmap = null; } /** * 给界面上的按钮及控件添加Listener */ public void setListener(){ preBundle = this.getIntent().getExtras(); subPicImgView = (ImageView)findViewById(R.id.subPicImgView); subButton = (Button)findViewById(R.id.subButton); returnButton = (Button)findViewById(R.id.returnMain); // stationSpinner = (Spinner)findViewById(R.id.stationId); subButton.setOnClickListener(subClick); returnButton.setOnClickListener(returnClick); helper = new DBHelper(this); helper.open(this); cursor = helper.loadAll(); cursor.moveToFirst(); if(!cursor.isAfterLast()){ int modelId = cursor.getColumnIndex("ID"); int stName = cursor.getColumnIndex("STNAME"); int stid = cursor.getColumnIndex("STID"); int addvcd = cursor.getColumnIndex("FATHER"); StationModel sm = new StationModel(); sm.setId(cursor.getInt(modelId)); sm.setStid(cursor.getInt(stid)); sm.setStname(cursor.getString(stName)); sm.setAddvcd(cursor.getString(addvcd)); list.add(sm); cursor.moveToNext(); } cursor.close(); helper.close(); } /** * 点击上传按钮触发 */ private OnClickListener subClick = new OnClickListener(){ public void onClick(View v) { ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo networkinfo = manager.getActiveNetworkInfo(); if (networkinfo == null || !networkinfo.isAvailable()) { // 当前网络不可用 new AlertDialog.Builder(SubmitPhoto.this) .setMessage("检查到没有可用的网络连接,请打开网络连接") .setPositiveButton("确定", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialoginterface, int i){ ComponentName cn = new ComponentName("com.android.settings","com.android.settings.Settings"); Intent intent = new Intent(); intent.setComponent(cn); intent.setAction("android.intent.action.VIEW"); startActivity(intent); // finish(); } } ).show(); }else{ showDialog(0); myThread = new MyThread(); myThread.start(); } } }; /** * 点击返回按钮时触发的事件 */ private OnClickListener returnClick = new OnClickListener(){ public void onClick(View v) { new AlertDialog.Builder(SubmitPhoto.this) .setTitle("提示").setMessage("确定放弃上传?") .setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // if(!myThread.isInterrupted()){ // myThread.interrupt(); // } Intent intent = new Intent(); intent.setClass(SubmitPhoto.this, MainPage.class); finish(); startActivity(intent); } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // 取消按钮事件 } } ).show(); } }; /** * 将上个界面传过来的图片地址转换成Bitmap返回 * @return */ public Bitmap getBitMap(){ String picPath = preBundle.getString("prePath"); BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 2; Bitmap bm = BitmapFactory.decodeFile(picPath, options); return bm; } /** * 当调用showDialog()时触发此函数 * 控制弹出的内容 */ @Override protected Dialog onCreateDialog(int id) { switch (id) { case 0: { ProgressDialog dialog = new ProgressDialog(SubmitPhoto.this); dialog.setMessage("文件上传中,请稍后..."); dialog.setIndeterminate(true); dialog.setCancelable(true); // Log.d("dialog","<<<<<<<<<<<<<<<<-----<<<<<<<<<dialoging"); return dialog; } case 1: { ProgressDialog mProgressDialog = new ProgressDialog(SubmitPhoto.this); mProgressDialog.setIcon(R.drawable.ic_menu_upload_mini); mProgressDialog.setTitle("文件上传中请稍后"); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setMax(100); mProgressDialog.setButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // removeDialog(1); } }); return mProgressDialog; } } return null; } /** * 显示Dialog的method * @param mess */ private void showToast(String mess) { // Log.d("showToast", "======================showToast"); new AlertDialog.Builder(SubmitPhoto.this).setTitle("Message") .setMessage(Html.fromHtml(mess)).setNegativeButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // if(!myThread.isInterrupted()){ // myThread.interrupt(); // } Intent intent = new Intent(); intent.setClass(SubmitPhoto.this, MainPage.class); finish(); startActivity(intent); } }).show(); } /* * 接收子线程传递过来的结果 * 负责给主线程发送消息 */ Handler subHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 0: showDialog(0); break; case 1: removeDialog(0); Bundle bundle = msg.getData(); // Log.d("upload result",">>>>>>>>>>>>>>>>>>upload result:"+bundle.getString("uploadMsg")); showToast(bundle.getString("uploadMsg")); break; case 2: removeDialog(0); showToast("您请求的网络连接失败,请稍后重试"); break; case 3: removeDialog(0); showToast("<p>对不起,您的手机卡没有被许可使用本程序进行上传功能,如有问题请<a href="mailto:[email protected]" mce_href="mailto:c.com">联系我们</a></p>"); break; } super.handleMessage(msg); } }; /** * 图片上传线程 * 将上传结果通过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):

 

本界面实现一个煎蛋的图像回廊,点击对应的图片后即跳转到图片编辑上传界面。

<?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):

 

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):

package com.bjwmt.camera; import java.util.List; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; public class ImageAdapter extends BaseAdapter { int mGalleryItemBackground; private Context mContext; private List<String> lis; public ImageAdapter(Context c,List<String> li) { mContext = c; lis=li; TypedArray a = mContext.obtainStyledAttributes(R.styleable.Gallery); mGalleryItemBackground = a.getResourceId( R.styleable.Gallery_android_galleryItemBackground, 0); a.recycle(); } public int getCount() { return lis.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ImageView i = new ImageView(mContext); Bitmap bm = BitmapFactory.decodeFile(lis.get(position).toString()); i.setImageBitmap(bm); i.setScaleType(ImageView.ScaleType.CENTER_CROP); i.setLayoutParams(new GridView.LayoutParams(88, 88)); i.setBackgroundResource(mGalleryItemBackground); i.setPadding(3,3,3,3); return i; } } 


转载请注明本文地址: 基于Android的 拍照上传 程序开发

猜你喜欢

转载自blog.csdn.net/wangchaoqi1985/article/details/80692379