Skip to content

Commit

Permalink
Merge pull request #1938 from as05071/master
Browse files Browse the repository at this point in the history
#6 #7 第六丶七次实验代码 #898
  • Loading branch information
zengsn authored Jun 15, 2019
2 parents 3c5277f + bdeeef7 commit c68267a
Show file tree
Hide file tree
Showing 3 changed files with 315 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package edu.hzuapps.androidlabs.soft1714080902218;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class DownloadFile extends AppCompatActivity {
protected static final int CHANGE_UI=1;
protected static final int ERROR=2;
private EditText et_path;
private ImageView iv;
//主线程创建消息处理器
private Handler handler=new Handler(){



public void handleMessage(android.os.Message msg){
if(msg.what==CHANGE_UI){
Bitmap bitmap=(Bitmap) msg.obj;
iv.setImageBitmap(bitmap);
}else if(msg.what==ERROR){
Toast.makeText(DownloadFile.this,"显示图片错误",Toast.LENGTH_SHORT).show();
}
};

};

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et_path=(EditText) findViewById(R.id.et_path);
iv=(ImageView) findViewById(R.id.iv);
}

public void click(View view){
final String path=et_path.getText().toString().trim();
if(TextUtils.isEmpty(path)){
Toast.makeText(this,"图片路径不能为空",Toast.LENGTH_SHORT).show();
}else {
//子线程请求网络,Android4.0以后访问网络不能放在主线程中
new Thread(){
private HttpURLConnection conn;
private Bitmap bitmap;
public void run(){
//连接服务器get请求,获取图片
try{
//创建URL对象
URL url=new URL(path);
//根据url发送http的请求
conn=(HttpURLConnection) url.openConnection();
//设置请求的方式
conn.setRequestMethod("GET");
//设置超时时间
conn.setConnectTimeout(5000);
//设置请求头User—Agent浏览器的版本
conn.setRequestProperty("User-Agent",
"Mozilla/4.0 (comparible;MSIE 6.0;Windows NT 5.1;"+"SV1; .NET4.0C;.NET4.0E;.NET CLR 2.0.50727;"
+".NET CLR 3.0.4506.2152;.NET CLR 3.5.30729;Shuame)");
//得到服务器返回的响应码
int code=conn.getResponseCode();
//请求网络成功后返回码是200
if(code==200){
//获取输入流
InputStream is=conn.getInputStream();
//将流转换成Bitmap对象
bitmap= BitmapFactory.decodeStream(is);
//TODO:告诉主线程一个消息:帮我更改界面。内容:bitmap
Message msg=new Message();
msg.what=CHANGE_UI;
msg.obj=bitmap;
handler.sendMessage(msg);
}else{
//返回码不是200,请求服务器失败
Message msg=new Message();
msg.what=ERROR;
handler.sendMessage(msg);
}
}catch (Exception e){
e.printStackTrace();
Message msg=new Message();
msg.what=ERROR;
handler.sendMessage(msg);
}
};
}.start();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
package edu.hzuapps.androidlabs.soft1714080902218;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Photo extends AppCompatActivity {
public static final int TAKE_PHOTO = 1;
public static final int CHOOSE_PHOTO = 2;
private ImageView picture;
private Uri imageUri;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photo);
Button takePhoto = (Button) findViewById(R.id.take_photo);
Button chooseFromAlbum = (Button) findViewById(R.id.choose_from_album);
picture = (ImageView) findViewById(R.id.picture);
takePhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
try {
if (outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= 24) {
imageUri = FileProvider.getUriForFile(Photo.this,
"com.example.cameraalbumtest.fileprovider", outputImage);
} else {
imageUri = Uri.fromFile(outputImage);
}
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, TAKE_PHOTO);
}
});

chooseFromAlbum.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(Photo.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.
PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(Photo.this, new
String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
} else {
openAlbum();
}
}
});
}

private void openAlbum() {
Intent intent = new Intent("android.intent.action.GET_CONTENT");
intent.setType("image/*");
startActivityForResult(intent, CHOOSE_PHOTO);
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openAlbum();
} else {
Toast.makeText(this, "You denied the permission",
Toast.LENGTH_SHORT).show();
}
break;
default:
;
}
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case TAKE_PHOTO:
if (resultCode == RESULT_OK) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
picture.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
case CHOOSE_PHOTO:
if (resultCode == RESULT_OK) {
if (Build.VERSION.SDK_INT >= 19) {
handleImageOnKitKat(data);
} else {
handleImageBeforeKitKat(data);
}
}
break;
default:
break;
}
}

private void handleImageBeforeKitKat(Intent data) {
Uri uri = data.getData();
String imagePath = getImagePath(uri, null);
displayImage(imagePath);
}

private void displayImage(String imagePath) {
if (imagePath != null) {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
picture.setImageBitmap(bitmap);
} else {
Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
}
}

private String getImagePath(Uri uri, String selection) {
String path = null;
Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();
}
return path;
}

@TargetApi(19)
private void handleImageOnKitKat(Intent data) {
String imagePath = null;
Uri uri = data.getData();
if (DocumentsContract.isDocumentUri(this, uri)) {
String docId = DocumentsContract.getDocumentId(uri);
if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
String id = docId.split(":")[1];
String selection = MediaStore.Images.Media._ID + "=" + id;
imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
} else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
imagePath = getImagePath(contentUri, null);
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
imagePath = getImagePath(uri, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
imagePath = uri.getPath();
}
displayImage(imagePath);
}

}
}
35 changes: 35 additions & 0 deletions students/soft1714080902218/res/layout/photo.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#FFBDFBF2"
tools:context=".Photo">

<Button
android:id="@+id/take_photo"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="?attr/colorAccent"
android:text="拍照" />


<Button
android:id="@+id/choose_from_album"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:background="?attr/colorAccent"
android:text="从相册中选择相片" />

<ImageView
android:id="@+id/picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />

</LinearLayout>

0 comments on commit c68267a

Please sign in to comment.