android的第一个小程序,调用相机拍照,访问网络图片

  继上次成功下载了android studio,虽然在使用过程中问题百出,但是到现在为止已经可以写一些简单的程序了。  

  上次说我在抄百度经验(链接)的的一个android使用手电筒的例子,出现了小问题,为解决这个问题花了不少时间,但是在抄这个小项目的源代码时又遇见了小问题

  这里竟然有一个小箭头,而我却不知道这是设么符号,所以源代码也抄不下去了,被卡在这,百度一下,都是一下答非所问的问题和答案,接下来我试了->和→这些符号,还是不行,于是就放弃了。

  但是老师要求我们去做一个app,这事又不能拖,硬着头皮就上了。先是获取一下服务器里的信息,这里我们的信息就是很简单的一张图片,对于android小白来说,简直就像是天书一样的要求。经过两年的学习,我们仿照自己的安卓手机:添加一个按钮,按下后会发送一个请求去服务器,访问到这个图片并显示出来。

  第一步怎么添加按钮。android stduio很贴心,将常用的组件信息都给列了出来,如下:

  只需要将button拖到界面上就会有button的信息,在Text中可以设置button的属性,这样按钮添加完成。仿照这按钮的添加,在加一个ImageView区域用于显示图片。

  写完以后,就是写按钮按下的触发事件了,这个可以在MainActivity中直接编写。加上一个监听,按下以后会触发发送信息的事件,然后在这里我们的经验实在有点少,onClick函数是抽象的,需要的是覆盖并实现方法,第一次,直接写在了onCreate函数中,不过功能也能实现。另外因为版本编辑过几次,前面的版本都没有备份,我的这个随笔到这为止,但下面的代码是几次版本后的,东西比我写的多,以后有时间会慢慢解释的。还要一个就是这里的本地图片选取功能没有实现,会闪退或者无法显示。

  配置信息activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:weightSum="1"
    tools:context="com.example.test.MainActivity">


    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        android:text="选择本地图片" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="camera"
        android:text="拍照选取图片" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="match_parent"
        android:layout_height="160dp" />


    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="49dp"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/radioButton2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="fgs" />

        <RadioButton
            android:id="@+id/radioButton3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="ifgs" />

        <RadioButton
            android:id="@+id/radioButton4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="rand_fgs" />

        <RadioButton
            android:id="@+id/radioButton5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="CW" />
    </RadioGroup>

    <Button
        android:id="@+id/butt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="获取网络图片" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="160dp" />


</LinearLayout>

  然后是主函数MainActivity.java

  1 package com.example.test;
  2 //android:onClick="gallery"
  3 import android.content.Intent;
  4 import android.database.Cursor;
  5 import android.graphics.Bitmap;
  6 import android.graphics.BitmapFactory;
  7 import android.net.Uri;
  8 import android.os.Environment;
  9 import android.os.StrictMode;
 10 import android.provider.MediaStore;
 11 import android.support.v7.app.AppCompatActivity;
 12 import android.os.Bundle;
 13 import android.text.TextUtils;
 14 import android.util.Log;
 15 import android.view.View;
 16 import android.widget.*;
 17 
 18 import java.io.File;
 19 import java.io.IOException;
 20 import java.io.InputStream;
 21 import java.lang.ref.PhantomReference;
 22 import java.net.HttpURLConnection;
 23 import java.net.URL;
 24 
 25 public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 26 
 27 
 28     public static Bitmap getBitmap(String path) throws IOException {
 29         URL url = new URL (path);
 30         HttpURLConnection conn = (HttpURLConnection)url.openConnection();
 31         conn.setConnectTimeout(5000);
 32         conn.setRequestMethod("GET");
 33         if(conn.getResponseCode() == 200){
 34             InputStream inputStream = conn.getInputStream();
 35             Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
 36             return bitmap;
 37         }
 38         return null;
 39     }
 40 
 41     //private Button but = null;
 42     private Button but2 = null;
 43 
 44     private static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
 45     private static final int SELECT_PIC_BY_PICK_PHOTO = 2;// 从相册中选择
 46     private static final int PHOTO_REQUEST_CUT = 3;// 结果
 47     private ImageView iv_image;
 48     private Button btn_pick_photo;   //开启相册
 49     private String picPath;   //图片路径
 50     /* 头像名称 */
 51     private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
 52     private File tempFile;
 53 
 54     @Override
 55     protected void onCreate(Bundle savedInstanceState) {
 56         super.onCreate (savedInstanceState);
 57         setContentView (R.layout.activity_main);
 58 
 59         //this.but=(Button) super.findViewById(R.id.button);
 60         this.but2= (Button)super.findViewById(R.id.butt);
 61         this.iv_image = (ImageView) this.findViewById (R.id.imageView2);
 62         btn_pick_photo = (Button) findViewById(R.id.button);
 63         btn_pick_photo.setOnClickListener(this);
 64 
 65         StrictMode.setThreadPolicy(new
 66                 StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
 67         StrictMode.setVmPolicy(
 68                 new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
 69 
 70         but2.setOnClickListener (new View.OnClickListener (){
 71 
 72             public void onClick(View v) {
 73                 //but2.setEnabled(false);
 74                 //but.setEnabled (true);
 75                 but2.setEnabled(true);
 76 
 77                 try {
 78                     int num = (int)(Math.random ()*10);
 79                     Bitmap img = getBitmap ("http://47.106.20.56:8080/mytest/"+num+".jpg");
 80                     ImageView myget=null;
 81                     myget=findViewById (R.id.imageView);
 82                     myget.setImageBitmap (img);
 83 
 84                     System.out.print ("hello");
 85                 }catch(IOException e){
 86                     e.printStackTrace ();
 87                 }
 88             }
 89         });
 90     }
 91     Bitmap bitmap2=null;
 92     @Override
 93     public void onClick(View v) {
 94         switch (v.getId()) {
 95             case R.id.button : // 开启图册
 96                 pickPhoto();
 97 
 98                 break;
 99             default :
100                 break;
101         }
102     }
103     /***
104      * 从相册中取图片
105      */
106     private void pickPhoto() {
107         Intent intent = new Intent(Intent.ACTION_PICK,
108                 android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
109         startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);
110        // bitmap2 = intent.getParcelableExtra ("intent");
111        // bitmap2=findViewById (R.id.imageView2);
112 
113     }
114     /*
115     从相册获取
116      */
117     /*
118     public void gallery(View view){
119         //激活图库,选择照片
120         Intent intent = new Intent(Intent.ACTION_PICK);
121         intent.setType ("imaage/*");
122         //开启一个带有返回值的Activity,请求码是PHOTO_EQUEST_GALLERY
123         startActivityForResult (intent,PHOTO_REQUEST_GALLERY);
124     }*/
125 
126     /*
127     从相机获取
128      */
129     public void camera(View view){
130         //激活相机
131         Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
132         //判断存储卡是否可用,可用进行存储
133         if(hasSdcard()){
134             tempFile = new File (Environment.getExternalStorageDirectory (),PHOTO_FILE_NAME);
135             //从文件创建uri
136             Uri uri = Uri.fromFile (tempFile);
137             intent.putExtra (MediaStore.EXTRA_OUTPUT,uri);
138         }
139         //开启一个带有返回值的Activity,请求码为PHOTO_EQUEST_CAREMA
140         startActivityForResult (intent,PHOTO_REQUEST_CAREMA);
141     }
142     /*
143     剪切图片
144      */
145     private void crop(Uri uri){
146         //裁剪图片意图
147         Intent intent = new Intent ("com.android.camera.action.CROP");
148         intent.setDataAndType (uri,"image/*");
149         intent.putExtra ("crop","true");
150         //裁剪框的比例1:1
151         intent.putExtra ("aspectX",1);
152         intent.putExtra ("aspectY",1);
153         //裁剪后输出图片的尺寸和大小
154         intent.putExtra ("outputX",250);
155         intent.putExtra ("outputY",250);
156 
157         intent.putExtra ("outputRormat","JPEG");//图片格式
158         intent.putExtra ("noFaceDetection",true);//取消人脸识别
159         intent.putExtra ("return-data",true);
160         //开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_CUT
161         startActivityForResult (intent,PHOTO_REQUEST_CUT);
162     }
163     /*
164     判断sdcard是否被挂载
165      */
166     private boolean hasSdcard(){
167         if(Environment.getExternalStorageState ().equals (Environment.MEDIA_MOUNTED)){
168             return true;
169 
170         }else{
171             return false;
172         }
173     }
174 
175     @Override
176     protected void onActivityResult(int resquestCode, int resultCode, Intent data){
177         if(resquestCode == SELECT_PIC_BY_PICK_PHOTO){
178             Uri uri = data.getData();
179 
180             //this.iv_image.setImageBitmap (bitmap);
181             if (!TextUtils.isEmpty(uri.getAuthority())) {
182                 //查询选择图片
183                 Cursor cursor = getContentResolver().query(
184                         uri,
185                         new String[] { MediaStore.Images.Media.DATA },
186                         null,
187                         null,
188                         null);
189                 //返回 没找到选择图片
190                 if (null == cursor) {
191                     return;
192                 }
193 
194                 //光标移动至开头 获取图片路径
195                 cursor.moveToFirst();
196                 picPath = cursor.getString(cursor
197                         .getColumnIndex(MediaStore.Images.Media.DATA));
198                // bitmap2 = data.getParcelableExtra ("data");
199                 //bitmap2=findViewById (R.id.imageView2);
200                 try{
201                     bitmap2 = getBitmap (uri.toString ());
202                 }catch(IOException e){
203                     e.printStackTrace ();
204                 }
205                 ImageView myget=null;
206                 myget=findViewById (R.id.imageView2);
207                 myget.setImageBitmap (bitmap2);
208                 //Log.d("图片路径啊啊啊啊啊啊",picPath);
209             }
210         }else if(resquestCode == PHOTO_REQUEST_CAREMA){
211             //从相机放回数据
212             if(hasSdcard ()) {
213                 crop (Uri.fromFile (tempFile));
214             }else{
215                 //Toast.makeText (MainActivity.this,"未找到存储卡,无法存储图片",0).show ();
216             }
217         }else if(resquestCode == PHOTO_REQUEST_CUT){
218             //剪切图片
219             if(data != null){
220                 Bitmap bitmap = data.getParcelableExtra ("data");
221                 this.iv_image.setImageBitmap (bitmap);
222             }
223             try{
224                 //删除临时文件
225                 tempFile.delete ();
226 
227             }catch(Exception e){
228                 e.printStackTrace ();
229             }
230 
231         }
232         super.onActivityResult(resquestCode,resultCode,data);
233     }
236 }

 

posted @ 2018-09-12 13:42  琥琥笙威  阅读(935)  评论(0编辑  收藏  举报