安卓开发之android 拍照和相册选择图片例子

 更新时间:2016年9月20日 19:52  点击:2010
android 拍照和相册选择图片这个在几乎只有用上传或拍照的app中都会有用到了,这里小编来为各位介绍一篇关于android 拍照和相册选择图片例子代码供各位参考,具体的如下所示。

android从选择图片有两种方法,但是返回值确不同,本文将指导大家如何统一这两种方式的返回值。

//关键代码
 @Event(R.id.btnPhoto)
    private void onBtnPhotoClicked(View view) {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, Config.Constants.CODE_PICK_IMAGE_FROM_PHOTO);
    }
 
    @Event(R.id.btnCamera)
    private void onBtnCameraClicked(View view) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, Config.Constants.CODE_PICK_IMAGE_FROM_CAMERA);
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case Config.Constants.CODE_PICK_IMAGE_FROM_CAMERA:
                if (data != null && data.hasExtra("data")) {
                    Bitmap bitmap = data.getParcelableExtra("data");
                    bitmap = BitmapUtil.scale(bitmap, 640.0f / bitmap.getWidth());
                    try {
                        File path = new File(((MyApplication) getApplication()).appPath, DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".jpg");
                        FileOutputStream outputStream = new FileOutputStream(path);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                        outputStream.close();
                        Intent intent = new Intent();
                        intent.putExtra("path", path.getAbsolutePath());
                        setResult(RESULT_OK, intent);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                finish();
                break;
            case Config.Constants.CODE_PICK_IMAGE_FROM_PHOTO:
                if(data != null){
                    Uri uri = data.getData();
                    Bitmap bitmap;
                    ContentResolver contentResolver = getContentResolver();
                    try {
                        bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri);
                        bitmap = BitmapUtil.scale(bitmap, 640.0f / bitmap.getWidth());
                        File path = new File(((MyApplication) getApplication()).appPath, DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".jpg");
                        FileOutputStream outputStream = new FileOutputStream(path);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                        outputStream.close();
                        Intent intent = new Intent();
                        intent.putExtra("path", path.getAbsolutePath());
                        setResult(RESULT_OK, intent);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                finish();
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
        }
    }
//BitmapUtil.java
public static Bitmap scale(Bitmap bitmap, float scale) {
    Matrix matrix = new Matrix();
    matrix.postScale(scale, scale);
    return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
 
//MyApplication
public File appPath;
 
@Override
public void onCreate() {
    super.onCreate();
    //创建目录
    appPath = new File(Environment.getExternalStorageDirectory(), getPackageName());
    if (!appPath.isDirectory()) {
        appPath.mkdir();
    }
}
经过统一处理之后,返回值均为图片的绝对路径地址。

华为P9将采用5.2英寸1080p屏幕,标准版采用麒麟950处理器+3GB内存+32GB机身存储,高配采用麒麟955处理器+4GB内存+64GB、128GB机身存储,下面我们来看看这篇介绍。

华为P9手机配置怎么样?双摄像头P9配置参数曝光

华为P9什么时候出?

P9发布会是4月6日。价格方面标准版 3088 元,高配版 3688 元

华为P9手机配置怎么样?

华为“??”图案正暗示其双镜头的设计。据悉将配备 5.2 ? 1080p 屏幕,麒麟 950,3G / 4G 内存,32GB 存储,1200W 双摄像头。价格方面标准版 3088 元,高配版 3688 元
华为P9采用双摄像头设计,并配备华为自主研发的传感器组合技术,支持重调焦距、模拟光圈调整、滤波镜应用等。由于其摄影光学系统是由德国著名光学品牌徕卡来调教,所以还会在机身上标记徕卡的“可乐标”

 

华为超薄新旗舰P9就长这样!配置售价大曝光

有网友曝光了一组P9以及保护套的渲染图,从图中来看,和之前曝光的一样,P9采用了背后双摄像头,配备双LED闪光灯。此外,指纹识别模块也同样设计在了背部。

手机侧面采用了金属中框,视觉上看起来很薄,背壳则是全金属材质。

android中apk的下载与自动安装这个虽然不推荐这样来做但有些朋友一定要问我如何实现了,这里整理了一些方法希望对各位有一些帮助了,具体如下。

手机中文件的下载分为后台自动下载和前台下载,我总结了这两种下的实现代码,其中前台下载并实现下载进度条的实现。


第一种:后台下载

/**
 * 后台在下面一个Apk 下载完成后返回下载好的文件
 *
 * @param httpUrl
 * @return
 */
 private File downFile(final String httpUrl) {

 new Thread(new Runnable() {

 @Override
 public void run() {
 try {
 URL url = new URL(httpUrl);
 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
 connection.setRequestMethod("GET");
 connection.setConnectTimeout(5000);
 FileOutputStream fileOutputStream = null;
 InputStream inputStream;
 if (connection.getResponseCode() == 200) {
 inputStream = connection.getInputStream();

 if (inputStream != null) {
 file = getFile(httpUrl);
 fileOutputStream = new FileOutputStream(file);
 byte[] buffer = new byte[1024];
 int length = 0;

 while ((length = inputStream.read(buffer)) != -1) {
 fileOutputStream.write(buffer, 0, length);
 }
 fileOutputStream.close();
 fileOutputStream.flush();
 }
 inputStream.close();
 }
 //下载完成
 //安装
 installApk();
 } catch (MalformedURLException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
 }).start();
 return file;
 }

 /**
 * 根据传过来url创建文件
 *
 */
 private File getFile(String url) {
 File files = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(), getFilePath(url));
 return files;
 }


 /**
 * 截取出url后面的apk的文件名
 *
 * @param url
 * @return
 */
 private String getFilePath(String url) {
 return url.substring(url.lastIndexOf("/"), url.length());
 }

 /**
 * 安装APK
 */
 private void installApk() {
 Intent intent = new Intent(Intent.ACTION_VIEW);
 intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
 startActivity(intent);
 }

 

第二种

//下载apk程序代码
 protected File downLoadFile(String httpUrl) {
                 // TODO Auto-generated method stub
                 final String fileName = "updata.apk";
                 File tmpFile = new File("/sdcard/update");
                 if (!tmpFile.exists()) {
                         tmpFile.mkdir();
                 }
                 final File file = new File("/sdcard/update/" + fileName);
 
                try {
                         URL url = new URL(httpUrl);
                         try {
                                 HttpURLConnection conn = (HttpURLConnection) url
                                                 .openConnection();
                                 InputStream is = conn.getInputStream();
                                 FileOutputStream fos = new FileOutputStream(file);
                                 byte[] buf = new byte[256];
                                 conn.connect();
                                 double count = 0;
                                 if (conn.getResponseCode() >= 400) {
                                         Toast.makeText(Main.this, "连接超时", Toast.LENGTH_SHORT)
                                                         .show();
                                 } else {
                                         while (count <= 100) {
                                                 if (is != null) {
                                                         int numRead = is.read(buf);
                                                         if (numRead <= 0) {
                                                                 break;
                                                         } else {
                                                                 fos.write(buf, 0, numRead);
                                                         }
 
                                                } else {
                                                         break;
                                                 }
 
                                        }
                                 }
 
                                conn.disconnect();
                                 fos.close();
                                 is.close();
                         } catch (IOException e) {
                                 // TODO Auto-generated catch block
 
                                e.printStackTrace();
                         }
                 } catch (MalformedURLException e) {
                         // TODO Auto-generated catch block
 
                        e.printStackTrace();
                 }
 
                return file;
         }
 //打开APK程序代码
 
private void openFile(File file) {
                 // TODO Auto-generated method stub
                 Log.e("OpenFile", file.getName());
                 Intent intent = new Intent();
                 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                 intent.setAction(android.content.Intent.ACTION_VIEW);
                 intent.setDataAndType(Uri.fromFile(file),
                                 "application/vnd.android.package-archive");
                 startActivity(intent);
}

上面这种方式直接调用downFile方法,参数传个URL地址就可以了

第三种:

private String url="http://----------------------.apk";
 private File file;
 private ProgressBar pb;
 private TextView tv;
 private int fileSize;
 private int downLoadFileSize;
 private String filename;
 private Handler handler = new Handler() {
 @Override
 public void handleMessage(Message msg) {//定义一个Handler,用于处理下载线程与UI间通讯
 if (!Thread.currentThread().isInterrupted()) {
 switch (msg.what) {
 case 0:
 pb.setMax(fileSize);
 case 1:
 pb.setProgress(downLoadFileSize);
 int result = downLoadFileSize * 100 / fileSize;
 tv.setText(result + "%");
 break;
 case 2:
 finish();
 openFile(file);
 break;
 case -1:
 String error = msg.getData().getString("error");
 Toast.makeText(DownLoadActivity.this, error, Toast.LENGTH_SHORT).show();
 break;
 }
 }
 super.handleMessage(msg);
 }
 };
new Thread() {
 public void run() {
 try {
 down_file(url, "/sdcard/");
 //下载文件,参数:第一个URL,第二个存放路径
 } catch (ClientProtocolException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 }
 }.start();
public void down_file(String url, String path) throws IOException {//下载函数
 filename = url.substring(url.lastIndexOf("/") + 1);//获取文件名
 URL myURL = new URL(url);
 URLConnection conn = myURL.openConnection();
 conn.connect();
 InputStream is = conn.getInputStream();
 this.fileSize = conn.getContentLength();//根据响应获取文件大小
 if (this.fileSize <= 0) throw new RuntimeException("无法获知文件大小 ");
 if (is == null) throw new RuntimeException("stream is null");
 FileOutputStream fos = new FileOutputStream(path + filename);//把数据存入路径+文件名

 byte buf[] = new byte[1024];
 downLoadFileSize = 0;
 sendMsg(0);
 do {
 //循环读取
 int numread = is.read(buf);
 if (numread == -1) {
 break;
 }
 fos.write(buf, 0, numread);
 downLoadFileSize += numread;
 sendMsg(1);//更新进度条
 } while (true);
 file = new File(path + filename);
 sendMsg(2);//通知下载完成
 try {
 is.close();
 } catch (Exception ex) {
 Log.e("tag", "error: " + ex.getMessage(), ex);
 }
 }

 private void sendMsg(int flag) {
 Message msg = new Message();
 msg.what = flag;
 handler.sendMessage(msg);
 }
 //打开APK程序代码

 private void openFile(File file) {
 // TODO Auto-generated method stub
 Log.e("OpenFile", file.getName());
 Intent intent = new Intent();
 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 intent.setAction(android.content.Intent.ACTION_VIEW);
 intent.setDataAndType(Uri.fromFile(file),
 "application/vnd.android.package-archive");
 startActivity(intent);
 }

Dialog是对话框了这个在js中就有一个Dialog命令了,现在在android开发中也有Dialog对话框了,我们下面来看小编整理的一些设置自定义Dialog的位置和大小例子吧,具体的细节如下所示。

在写代码用到对话框的时候,很多时候需要我们自己去搭建对话框的布局,也就是说要自定义dialog,然后在运行出效果的时候,往往对话框大小不成比例,位置也是默认居中的,很不符合我们的需求,下面贴上一部分代码来自定义对话框的位置和大小。

例子1

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

public class MainActivity extends Activity {
 TextView tv;
 TextView tv2;
 private Dialog dialog;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 tv= (TextView) findViewById(R.id.tv);
 tv.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 dialog.show();
 }
 });
 //加载对话框
 View view = View.inflate(MainActivity.this,
 R.layout.dialog_register, null);

 dialog = new Dialog(MainActivity.this, R.style.MyDialogStyleBottom);
 dialog.setCanceledOnTouchOutside(false);
 tv2= (TextView) view.findViewById(R.id.tv_yes);
 dialog.setContentView(view);

 tv2.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 dialog.dismiss();
 }
 });

 Window dialogWindow = dialog.getWindow();
 WindowManager.LayoutParams lp = dialogWindow.getAttributes();
 dialogWindow.setGravity(Gravity.CENTER);
 WindowManager m = getWindowManager();
 Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
 WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
 //p.height = (int) (d.getHeight() * 0.3); // 高度设置为屏幕的0.3
 p.width = (int) (d.getWidth() * 0.85); // 宽度设置为屏幕的0.85
 dialogWindow.setAttributes(p);

 }
}

例子2

自定义对话框(Dialog)位置,大小
package angel.devil;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;

public class DialogDemoActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Dialog dialog = new Dialog(this);
       
        // setContentView可以设置为一个View也可以简单地指定资源ID
        // LayoutInflater
        // li=(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
        // View v=li.inflate(R.layout.dialog_layout, null);
        // dialog.setContentView(v);
        dialog.setContentView(R.layout.dialog_layout);

        dialog.setTitle("Custom Dialog");

        /*
         * 获取圣诞框的窗口对象及参数对象以修改对话框的布局设置,
         * 可以直接调用getWindow(),表示获得这个Activity的Window
         * 对象,这样这可以以同样的方式改变这个Activity的属性.
         */
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.LEFT | Gravity.TOP);

        /*
         * lp.x与lp.y表示相对于原始位置的偏移.
         * 当参数值包含Gravity.LEFT时,对话框出现在左边,所以lp.x就表示相对左边的偏移,负值忽略.
         * 当参数值包含Gravity.RIGHT时,对话框出现在右边,所以lp.x就表示相对右边的偏移,负值忽略.
         * 当参数值包含Gravity.TOP时,对话框出现在上边,所以lp.y就表示相对上边的偏移,负值忽略.
         * 当参数值包含Gravity.BOTTOM时,对话框出现在下边,所以lp.y就表示相对下边的偏移,负值忽略.
         * 当参数值包含Gravity.CENTER_HORIZONTAL时
         * ,对话框水平居中,所以lp.x就表示在水平居中的位置移动lp.x像素,正值向右移动,负值向左移动.
         * 当参数值包含Gravity.CENTER_VERTICAL时
         * ,对话框垂直居中,所以lp.y就表示在垂直居中的位置移动lp.y像素,正值向右移动,负值向左移动.
         * gravity的默认值为Gravity.CENTER,即Gravity.CENTER_HORIZONTAL |
         * Gravity.CENTER_VERTICAL.
         *
         * 本来setGravity的参数值为Gravity.LEFT | Gravity.TOP时对话框应出现在程序的左上角,但在
         * 我手机上测试时发现距左边与上边都有一小段距离,而且垂直坐标把程序标题栏也计算在内了,
         * Gravity.LEFT, Gravity.TOP, Gravity.BOTTOM与Gravity.RIGHT都是如此,据边界有一小段距离
         */
        lp.x = 100; // 新位置X坐标
        lp.y = 100; // 新位置Y坐标
        lp.width = 300; // 宽度
        lp.height = 300; // 高度
        lp.alpha = 0.7f; // 透明度

        // 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
        // dialog.onWindowAttributesChanged(lp);
        dialogWindow.setAttributes(lp);

        /*
         * 将对话框的大小按屏幕大小的百分比设置
         */
//        WindowManager m = getWindowManager();
//        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
//        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
//        p.height = (int) (d.getHeight() * 0.6); // 高度设置为屏幕的0.6
//        p.width = (int) (d.getWidth() * 0.65); // 宽度设置为屏幕的0.65
//        dialogWindow.setAttributes(p);

        dialog.show();

    }
}

 

 

布局文件:

main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#00FF00"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

</LinearLayout>

 

dialog_layout.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:padding="10dp" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dp"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="A Dialog"
        android:textColor="#FFF" />

</LinearLayout>

[!--infotagslink--]

相关文章

  • 苹果告别“高大上”,越来越向安卓和中国用户靠近

    “一起,让我们将这个世界变得更好。”苹果首席执行官蒂姆 库克对着台下5000多名开发者说道,声音略有些沙哑和颤抖。...2016-07-04
  • 使用PHP+JavaScript将HTML页面转换为图片的实例分享

    这篇文章主要介绍了使用PHP+JavaScript将HTML元素转换为图片的实例分享,文后结果的截图只能体现出替换的字体,也不能说将静态页面转为图片可以加快加载,只是这种做法比较interesting XD需要的朋友可以参考下...2016-04-19
  • C#从数据库读取图片并保存的两种方法

    这篇文章主要介绍了C#从数据库读取图片并保存的方法,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...2021-01-16
  • Python 图片转数组,二进制互转操作

    这篇文章主要介绍了Python 图片转数组,二进制互转操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-09
  • Android子控件超出父控件的范围显示出来方法

    下面我们来看一篇关于Android子控件超出父控件的范围显示出来方法,希望这篇文章能够帮助到各位朋友,有碰到此问题的朋友可以进来看看哦。 <RelativeLayout xmlns:an...2016-10-02
  • Photoshop古装美女图片转为工笔画效果制作教程

    今天小编在这里就来给各位Photoshop的这一款软件的使用者们来说说把古装美女图片转为细腻的工笔画效果的制作教程,各位想知道方法的使用者们,那么下面就快来跟着小编一...2016-09-14
  • php抓取网站图片并保存的实现方法

    php如何实现抓取网页图片,相较于手动的粘贴复制,使用小程序要方便快捷多了,喜欢编程的人总会喜欢制作一些简单有用的小软件,最近就参考了网上一个php抓取图片代码,封装了一个php远程抓取图片的类,测试了一下,效果还不错分享...2015-10-30
  • jquery左右滚动焦点图banner图片鼠标经过显示上下页按钮

    jquery左右滚动焦点图banner图片鼠标经过显示上下页按钮...2013-10-13
  • Android开发中findViewById()函数用法与简化

    findViewById方法在android开发中是获取页面控件的值了,有没有发现我们一个页面控件多了会反复研究写findViewById呢,下面我们一起来看它的简化方法。 Android中Fin...2016-09-20
  • Android模拟器上模拟来电和短信配置

    如果我们的项目需要做来电及短信的功能,那么我们就得在Android模拟器开发这些功能,本来就来告诉我们如何在Android模拟器上模拟来电及来短信的功能。 在Android模拟...2016-09-20
  • 夜神android模拟器设置代理的方法

    夜神android模拟器如何设置代理呢?对于这个问题其实操作起来是非常的简单,下面小编来为各位详细介绍夜神android模拟器设置代理的方法,希望例子能够帮助到各位。 app...2016-09-20
  • android自定义动态设置Button样式【很常用】

    为了增强android应用的用户体验,我们可以在一些Button按钮上自定义动态的设置一些样式,比如交互时改变字体、颜色、背景图等。 今天来看一个通过重写Button来动态实...2016-09-20
  • Android WebView加载html5页面实例教程

    如果我们要在Android应用APP中加载html5页面,我们可以使用WebView,本文我们分享两个WebView加载html5页面实例应用。 实例一:WebView加载html5实现炫酷引导页面大多...2016-09-20
  • 深入理解Android中View和ViewGroup

    深入理解Android中View和ViewGroup从组成架构上看,似乎ViewGroup在View之上,View需要继承ViewGroup,但实际上不是这样的。View是基类,ViewGroup是它的子类。本教程我们深...2016-09-20
  • Photoshop枪战电影海报图片制作教程

    Photoshop的这一款软件小编相信很多的人都已经是使用过了吧,那么今天小编在这里就给大家带来了用Photoshop软件制作枪战电影海报的教程,想知道制作步骤的玩家们,那么下面...2016-09-14
  • Android自定义WebView网络视频播放控件例子

    下面我们来看一篇关于Android自定义WebView网络视频播放控件开发例子,这个文章写得非常的不错下面给各位共享一下吧。 因为业务需要,以下代码均以Youtube网站在线视...2016-10-02
  • Android用MemoryFile文件类读写进行性能优化

    java开发的Android应用,性能一直是一个大问题,,或许是Java语言本身比较消耗内存。本文我们来谈谈Android 性能优化之MemoryFile文件读写。 Android匿名共享内存对外A...2016-09-20
  • python opencv通过4坐标剪裁图片

    图片剪裁是常用的方法,那么如何通过4坐标剪裁图片,本文就详细的来介绍一下,感兴趣的小伙伴们可以参考一下...2021-06-04
  • 安卓开发之设置密码只能输入字母和数字的组合

    设置登录密码我们一般会有限制的如由什么组合了,下面我们来看一篇关于安卓开发之设置密码只能输入字母和数字的组合方法,具体的细节如下所示。 无论是电脑还是手机...2016-09-20
  • Android设置TextView竖着显示实例

    TextView默认是横着显示了,今天我们一起来看看Android设置TextView竖着显示如何来实现吧,今天我们就一起来看看操作细节,具体的如下所示。 在开发Android程序的时候,...2016-10-02