首页 > 编程技术 > android

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

发布时间:2016-9-20 19:52

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--]

您可能感兴趣的文章: