标签:
一、Android 权限配置文件:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.niewei.updatefile" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="14" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="com.xiaomi.market.sdk.UPDATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.READ_LOGS" /> <uses-permission android:name="android.permission.CALL_PHONE" /> <uses-permission android:name="android.permission.GET_TASKS" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.SET_DEBUG_APP" /> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> <uses-permission android:name="android.permission.USE_CREDENTIALS" /> <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" /> <!-- 权限 : GPS定位 --> <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" /> <!-- 权限 : AGPS定位 --> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.NFC" /> <uses-feature android:name="android.hardware.camera" /> <uses-feature android:name="android.hardware.camera.autofocus" /> <!-- 联网 --> <!-- 创建和删除文件 --> <!-- 写文件 --> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_APN_SETTINGS" /> <!-- 接收短信权限 --> <uses-permission android:name="android.permission.READ_SMS" /> <uses-permission android:name="android.permission.WRITE_SMS" /> <uses-permission android:name="android.permission.RECEIVE_SMS" /> <!-- 发送短信权限 --> <uses-permission android:name="android.permission.SEND_SMS" /> <!-- 拨打电话权限 --> <!-- 完全退出程序 --> <uses-permission android:name="android.permission.RESTART_PACKAGES" /> <!-- 统计 --> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.CHANGE_CONFIGURATION" /> <!-- 桌面快捷方式 --> <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" /> <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" /> <uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" /> </manifest>
二、Android 界面文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingBottom="10dp" tools:context="${relativePackage}.${activityClass}" > <LinearLayout android:id="@+id/btn_layout" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:id="@+id/Openbtn" android:layout_width="fill_parent" android:layout_height="40sp" android:layout_weight="1" android:layout_marginLeft="10sp" android:layout_marginRight="10sp" android:gravity="center" android:text="选择图片" android:textColor="#ffffffff" android:textSize="15sp" /> <Button android:id="@+id/Editbtn" android:layout_width="fill_parent" android:layout_height="40sp" android:layout_weight="1" android:layout_marginLeft="10sp" android:layout_marginRight="10sp" android:gravity="center" android:text="裁剪图片" android:textColor="#ffffffff" android:textSize="15sp" /> </LinearLayout> <Button android:id="@+id/button_updateimage" android:layout_width="fill_parent" android:layout_height="40sp" android:layout_marginLeft="10sp" android:layout_marginRight="10sp" android:layout_marginTop="2sp" android:gravity="center" android:text="上传图片" android:textColor="#ffffffff" android:textSize="15sp" android:layout_below="@+id/btn_layout" /> <ImageView android:id="@+id/img" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_below="@+id/button_updateimage" android:scaleType="centerInside" /> </RelativeLayout>
三、Android 界面程序文件:
package com.niewei.updatefile; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Date; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.InputStreamEntity; import org.apache.http.impl.client.DefaultHttpClient; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; public class MainActivity extends Activity { static String LogTag="Assets_NieweiSnop"; private static final int TAKE_PICTURE = 0; private static final int CHOOSE_PICTURE = 1; private static final int CROP = 2; private static final int CROP_PICTURE = 3; private static final int SCALE = 2;//照片缩小比例 private ImageView iv_image = null; Bitmap bitmap;//选择后的图片 private static final int SET1 = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); iv_image = (ImageView) this.findViewById(R.id.img); this.findViewById(R.id.Openbtn).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //即拍即显示 showPicturePicker(MainActivity.this,false); } }); this.findViewById(R.id.Editbtn).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //截图后显示 showPicturePicker(MainActivity.this,true); } }); this.findViewById(R.id.button_updateimage).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //上传服务器 try { new Thread(new NewThread()).start(); } catch (Exception e) { //e.printStackTrace(); Log.e(LogTag, e.getMessage()); } } }); } static String FilePath=""; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { switch (requestCode) { case TAKE_PICTURE: //将保存在本地的图片取出并缩小后显示在界面上 bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+"/image.jpg"); FilePath=Environment.getExternalStorageDirectory()+"/image.jpg"; Log.e(LogTag, "拍照文件路径 :"+FilePath); Bitmap newBitmap = ImageTools.zoomBitmap(bitmap, bitmap.getWidth() / SCALE, bitmap.getHeight() / SCALE); //由于Bitmap内存占用较大,这里需要回收内存,否则会报out of memory异常 bitmap.recycle(); //将处理过的图片显示在界面上,并保存到本地 iv_image.setImageBitmap(newBitmap); ImageTools.savePhotoToSDCard(newBitmap, Environment.getExternalStorageDirectory().getAbsolutePath(), String.valueOf(System.currentTimeMillis())); break; case CHOOSE_PICTURE: try { Uri uri = data.getData();//得到uri,后面就是将uri转化成file的过程。 String[] proj = {MediaStore.Images.Media.DATA}; Cursor actualimagecursor = managedQuery(uri, proj, null, null, null); int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); actualimagecursor.moveToFirst(); String img_path = actualimagecursor.getString(actual_image_column_index); File file = new File(img_path); // Toast.makeText(MainActivity.this, file.toString(), Toast.LENGTH_SHORT).show(); Log.e(LogTag, "第一次选择文件路径 :"+file.toString()); FilePath=file.toString(); } catch (Exception e) { e.printStackTrace(); } ContentResolver resolver = getContentResolver(); //照片的原始资源地址 Uri originalUri = data.getData(); try { //使用ContentProvider通过URI获取原始图片 Bitmap photo = MediaStore.Images.Media.getBitmap(resolver, originalUri); if (photo != null) { //为防止原始图片过大导致内存溢出,这里先缩小原图显示,然后释放原始Bitmap占用的内存 Bitmap smallBitmap = ImageTools.zoomBitmap(photo, photo.getWidth() / SCALE, photo.getHeight() / SCALE); //释放原始图片占用的内存,防止out of memory异常发生 photo.recycle(); iv_image.setImageBitmap(smallBitmap); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } break; case CROP: Uri uri = null; if (data != null) { uri = data.getData(); System.out.println("Data"); }else { System.out.println("File"); String fileName = getSharedPreferences("temp",Context.MODE_WORLD_WRITEABLE).getString("tempName", ""); uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),fileName)); } cropImage(uri, 500, 500, CROP_PICTURE); break; case CROP_PICTURE: Bitmap photo = null; Uri photoUri = data.getData(); if (photoUri != null) { photo = BitmapFactory.decodeFile(photoUri.getPath()); } if (photo == null) { Bundle extra = data.getExtras(); if (extra != null) { photo = (Bitmap)extra.get("data"); ByteArrayOutputStream stream = new ByteArrayOutputStream(); photo.compress(Bitmap.CompressFormat.JPEG, 100, stream); } } iv_image.setImageBitmap(photo); break; default: break; } } } public void showPicturePicker(Context context,boolean isCrop){ final boolean crop = isCrop; AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("图片来源"); builder.setNegativeButton("取消", null); builder.setItems(new String[]{"拍照","相册"}, new DialogInterface.OnClickListener() { //类型码 int REQUEST_CODE; @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case TAKE_PICTURE: Uri imageUri = null; String fileName = null; Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (crop) { REQUEST_CODE = CROP; //删除上一次截图的临时文件 SharedPreferences sharedPreferences = getSharedPreferences("temp",Context.MODE_WORLD_WRITEABLE); ImageTools.deletePhotoAtPathAndName(Environment.getExternalStorageDirectory().getAbsolutePath(), sharedPreferences.getString("tempName", "")); //保存本次截图临时文件名字 fileName = String.valueOf(System.currentTimeMillis()) + ".jpg"; Editor editor = sharedPreferences.edit(); editor.putString("tempName", fileName); editor.commit(); }else { REQUEST_CODE = TAKE_PICTURE; fileName = "image.jpg"; } imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),fileName)); //指定照片保存路径(SD卡),image.jpg为一个临时文件,每次拍照后这个图片都会被替换 openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(openCameraIntent, REQUEST_CODE); break; case CHOOSE_PICTURE: Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT); if (crop) { REQUEST_CODE = CROP; }else { REQUEST_CODE = CHOOSE_PICTURE; } openAlbumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); startActivityForResult(openAlbumIntent, REQUEST_CODE); break; default: break; } } }); builder.create().show(); } //截取图片 public void cropImage(Uri uri, int outputX, int outputY, int requestCode){ Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); intent.putExtra("outputX", outputX); intent.putExtra("outputY", outputY); intent.putExtra("outputFormat", "JPEG"); intent.putExtra("noFaceDetection", true); intent.putExtra("return-data", true); startActivityForResult(intent, requestCode); } @SuppressLint("HandlerLeak") private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case SET1: Log.e(LogTag, "照片执行"); //GetWeather4(msg.obj.toString()) ; break; } } }; int requestTime=0; private class NewThread implements Runnable { public void run() { try { //Bitmap smallBitmap = ImageTools.zoomBitmap(bitmap, bitmap.getWidth() / SCALE, bitmap.getHeight() / SCALE); //将保存在本地的图片取出并缩小后显示在界面上 bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+"/image.jpg"); Bitmap newBitmaps = ImageTools.zoomBitmap(bitmap, bitmap.getWidth() / SCALE, bitmap.getHeight() / SCALE); //由于Bitmap内存占用较大,这里需要回收内存,否则会报out of memory异常 bitmap.recycle(); // String img=JsonImgHelper.bitmaptoString(newBitmaps,70); // Log.e(LogTag, "照片字符串长度 "+String.valueOf(img.length())); Date curDateStart =new Date(System.currentTimeMillis());//获取当前时间 // TODO Auto-generated method stub HttpClient hc = new DefaultHttpClient(); String SerIp="http://192.168.1.142:7575/MainService.svc/update_pictrue"; // SerIp="http://192.168.1.142:7373/Service.svc/update_pictrue"; HttpPost hp = new HttpPost(SerIp); HttpResponse hr; InputStreamEntity reqEntity; String path = FilePath; File f = new File(path); if (f.exists()) { System.out.println("successful"); try { reqEntity = new InputStreamEntity(new FileInputStream(path), -1); reqEntity.setContentType("binary/octet-stream"); reqEntity.setChunked(true); // Send in multiple parts if needed hp.setEntity(reqEntity); Log.e(LogTag, "新方法 文件上传:"+"步骤 "+"4"); HttpResponse response = hc.execute(hp); Log.e(LogTag, "新方法 文件上传:"+"步骤 "+"5"); Date curDateEnd =new Date(System.currentTimeMillis());//获取当前时间 long diff = curDateEnd.getTime() - curDateStart.getTime();//这样得到的差值是微秒级别 Log.e(LogTag, "新方法 文件上传 :"+"总计用时 "+String.valueOf(diff)+"毫秒"); } catch (ClientProtocolException e) { Log.e(LogTag,e.getMessage()); } catch (IOException e) { Log.e(LogTag,e.getMessage()); } } // Message msg = MainActivity.this.handler // .obtainMessage(MainActivity.SET1, jonString); // MainActivity.this.handler.sendMessage(msg); } catch (Exception e) { Log.e(LogTag, e.getMessage()); } finally { } } } }
四、WCF程序配置代码:
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.serviceModel> <bindings> <webHttpBinding> <binding name="NewBinding0" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" transferMode="Streamed"> <readerQuotas maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" /> <security mode="None"></security> </binding> </webHttpBinding> </bindings> <behaviors> <serviceBehaviors> <behavior name=""> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="httpBehavior"> <webHttp/> </behavior> </endpointBehaviors> </behaviors> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> <services> <service name="AndroidWebServer.MainService"> <endpoint address="" behaviorConfiguration="httpBehavior" binding="webHttpBinding" bindingConfiguration="NewBinding0" contract="AndroidWebServer.IMainService" /> </service> </services> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> <directoryBrowse enabled="true"/> </system.webServer> </configuration>
五、WCF程序接口代码:
[OperationContract] [WebInvoke(BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] string update_pictrue(Stream getStream);
六、WCF程序接口实现代码:
string uploadFolder = @"C:\kkk\"; string savaPath = @"Photo\"; public string update_pictrue(Stream getStream) { LW.LogEvent("setData service has bean started!", EventLogEntryType.Error); string fileName = Guid.NewGuid().ToString() + ".jpg"; FileStream targetStream = null; if (!getStream.CanRead) { LW.LogEvent("数据流不可读!", EventLogEntryType.Error); } if (savaPath == null) savaPath = @"Photo\"; if (!savaPath.EndsWith("\\")) savaPath += "\\"; uploadFolder = uploadFolder + savaPath; //+ dateString; if (!Directory.Exists(uploadFolder)) { Directory.CreateDirectory(uploadFolder); } string filePath = Path.Combine(uploadFolder, fileName); using (targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None)) { const int bufferLen = 4096; byte[] buffer = new byte[bufferLen]; int count = 0; while ((count = getStream.Read(buffer, 0, bufferLen)) > 0) { targetStream.Write(buffer, 0, count); } targetStream.Close(); getStream.Close(); LW.LogEvent("文件写入完毕 " + fileName, EventLogEntryType.Error); } return ""; }
标签:
原文地址:http://www.cnblogs.com/qq458978/p/5729628.html