android使用wcf接收上传图片视频文件

一、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 "";
        }
时间: 2024-08-01 14:46:05

android使用wcf接收上传图片视频文件的相关文章

如何扫描出Android系统媒体库中视频文件

Android系统启动时会去扫描系统文件,并将系统支持的视频文件(mp4,3gp,wmv)扫描到媒体库(MediaStore)中,下面代码演示如何获得这些文件的信息: publicstatic List<VideoInfo> sysVideoList = null;// 视频信息集合 sysVideoList = new ArrayList<VideoInfo>();   setVideoList(); privatevoid setVideoList() {   // Media

Android:通过ThumbnailUtils类获取视频文件的缩略图

在视频播放器上经常会看到,有很多的视频缩略图,本文讲的就是通过ThumbnailUtils类获取视频文件的缩略图; 运行截图如下: 代码如下: MainActivity.java: package com.vrinux.thumbnailutilsdemo; import android.app.Activity; import android.graphics.Bitmap; import android.media.ThumbnailUtils; import android.os.Bund

Android使用OKHttp库实现视频文件的上传到服务器

目录 1 服务器接口简介 2 Android端代码实现 2.1 xml布局文件 2.2 Activity类 2.3 Okhttp网络通信类 1 服务器接口简介 此处我使用的服务器接口是使用Flask编写,具体实现代码: # -*- coding: utf-8 -*- from flask import Flask, render_template, jsonify, request import time import os import base64 app = Flask(__name__)

android上传图片、视频、文件,服务端使用wcf接收

最近一直在搞android上传图片.视频.文件,服务端使用wcf接收,本文对调试中的遇到的问题进行记录. 首先android上传一些小图片是比较容易的一天下来差不多就能调试出来,但是上传一些大的文件时就出现各种问题,包括wcf默认支持64k的文件,后来大图片可以上传了,但是传视频又有问题,上传的视频打不开,经过努力google最后问题终于解决了.作者kwstu QQ806693619 以下是调试代码:原文链接:http://www.kwstu.com/ArticleView/kwstu_2013

Android 打开/播放电脑的音频/视频文件

今天早上一到办公室,照常打开博客园看文章,看到有一片文章是用  http://www.cnblogs.com/wdfrog/p/3738180.html 看到这哥们实现的方法好复杂,又是配置电脑端,又是配置手机端,还又是转码啥的,倒腾时间长不说,而且还很麻烦,这里介绍下我是如何用手机直接播放电脑上的文件的. 之所以播放电脑上的文件,主要原因是视频文件都很大,清晰度高的一部电影都1GB左右了,对于手机来说,虽然能够装得下,但是看完就得删了,没法长时间储存在手机上, 来回往手机上拷视频文件,就这文件

笔记-Android中打开各种格式的文件(apk、word、excel、ppt、pdf、音视频、图片等)

打开后缀.apk的文件,即启动安装程序: //apkFilePath 文件路径 public void installAPK(String apkFilePath) { // 创建URI Uri uri = Uri.fromFile(new File(apkFilePath)); Intent intent = new Intent(Intent.ACTION_VIEW); // 设置Uri和类型 intent.setDataAndType(uri, "application/vnd.andro

Android必知必会-获取视频文件的截图、缩略图

背景 公司最近要求给我负责的APP加上视频录制和发布的功能,我简单的完成了基本的录制和视频压缩功能,后来发现发布接口需要上传视频的截图,网上搜索了一下资料,在这里整理一下. 代码实现 /** * 获取视频文件截图 * * @param path 视频文件的路径 * @return Bitmap 返回获取的Bitmap */ public static Bitmap getVideoThumb(String path) { MediaMetadataRetriever media = new Me

Android 播放视频文件

1 package com.example.myvideo2; 2 3 import java.io.File; 4 5 import android.app.Activity; 6 import android.net.Uri; 7 import android.os.Bundle; 8 import android.os.Environment; 9 import android.view.Menu; 10 import android.view.MenuItem; 11 import an

android 中获取视频文件的缩略图(非原创)

在android中获取视频文件的缩略图有三种方法: 1.从媒体库中查询 2. android 2.2以后使用ThumbnailUtils类获取 3.调用jni文件,实现MediaMetadataRetriever类 三种方法各有利弊 第一种方法,新视频增加后需要SDCard重新扫描才能给新增加的文件添加缩略图,灵活性差,而且不是很稳定,适合简单应用 第二种方法,实现简单,但2.2以前的版本不支持 第三种方法,实现复杂,但比较灵活,推荐使用 下面给出三种方法的Demo 1.第一种方法: publi