• 外部存储 使用详解


    极力推荐文章:欢迎收藏
    Android 干货分享

    阅读五分钟,每日十点,和您一起终身学习,这里是程序员Android

    本篇文章主要介绍 Android 开发中的部分知识点,通过阅读本篇文章,您将收获以下内容:

    1. 保存外部存储需要申请权限
    2. 外部存储使用案例(保存,读取,删除图片)

    Android 设备支持外部存储,比如SD卡等,保存在外部存储的数据具有全局可读性,可供在其他设备比如电脑上阅读,修改等。使用外部存储需要获取外部存储的访问权限<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    1. 保存外部存储需要申请权限

    这个很重要,不然无法操作SD 卡,

       <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

    2. 外部存储使用案例(保存,读取,删除图片)

    • 实现效果

    外部存储保存图片的方法

    判断是否挂载 SD 卡方法

    	/**
    	 * 1.判断SD卡是否挂载
    	 * **/
    	public static boolean isMounted() {
    
    		String state = Environment.getExternalStorageState();
    		return state.equals(Environment.MEDIA_MOUNTED);
    
    	}
    
    • SD 保存图片,删除图片、显示图片的方法

    保存图片到SD卡

    保存图片到SD卡 实现代码如下:

    	// 保存图片的方法
    	public void BtnSaveImage(View view) {
    		// 获取图片类型 bitmap
    		Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
    				R.drawable.ic_launcher);
    
    		ByteArrayOutputStream baos = new ByteArrayOutputStream();
    		// 将bitmap 压缩成byte类型 并保存到outputstream中
    		bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
    		bitmap.recycle();
    		boolean saveimg = SaveImg(getApplicationContext(), "photo.png",
    				baos.toByteArray());
    		if (saveimg) {
    			Toast.makeText(getApplicationContext(), "保存成功" + store_path,
    					Toast.LENGTH_SHORT).show();
    		}
    		try {
    			baos.close();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    
    	// 保存图片的方法
    	public static boolean SaveImg(Context context, String filename, byte[] data) {
    		// 判断是否挂载SD卡
    		if (!isMounted()) {
    			Toast.makeText(context, "SD卡未安装", Toast.LENGTH_SHORT).show();
    			return false;
    		}
    		File dir = new File(store_path);
    		// 创建文件目录
    		if (!dir.exists()) {
    			dir.mkdirs();
    		}
    		try {
    			// 向文件目录 dir中写文件filename
    			FileOutputStream fos = new FileOutputStream(new File(dir, filename));
    			fos.write(data);
    			fos.close();
    			return true;
    
    		} catch (IOException e) {
    			e.printStackTrace();
    			Log.i("TAG", "IOException..." + e);
    			return false;
    		}
    	}
    
    

    删除图片的方法

    删除图片 代码实现代码实现如下:

    	public void BtnDeleteImage(View view) {
    		DeletleImg(getApplicationContext(), "photo.png");
    
    	}
    
    	// 删除图片
    	public static void DeletleImg(Context context, String filename) {
    
    		File dirfile = new File(store_path + filename);
    		// 判断文件是否存在
    		if (!dirfile.exists()) {
    			Toast.makeText(context, "文件不存在", Toast.LENGTH_SHORT).show();
    			return;
    		}
    		if (dirfile.isDirectory()) {
    			String[] childdir = dirfile.list();
    			for (int i = 0; i < childdir.length; i++) {
    				new File(dirfile, childdir[i]).delete();
    			}
    		}
    		dirfile.delete();
    	}
    

    读取显示图片的方法

    读取显示图片代码实现如下:

    // 读取图片
    	public void BtnReadImage(View view) {
    		Bitmap readImg = ReadImg(getApplicationContext(), "photo.png");
    		if (readImg == null) {
    			Toast.makeText(getApplicationContext(), "读取失败" + store_path,
    					Toast.LENGTH_SHORT).show();
    		} else {
    			((ImageView) findViewById(R.id.img_external))
    					.setImageBitmap(readImg);
    		}
    
    	}
    
    	// 读取图片
    	public static Bitmap ReadImg(Context context, String filename) {
    		// 判断是否挂载SD卡
    		if (!isMounted()) {
    			Toast.makeText(context, "SD卡未安装", Toast.LENGTH_SHORT).show();
    			return null;
    		}
    		// 获取文件路径下的文件名称
    		File imgFile = new File(store_path, filename);
    		if (imgFile.exists()) {
    			Log.i("TAG", "imgFile" + imgFile.getAbsolutePath());
    			// 将路径下的文件转换成 bitmap
    			return BitmapFactory.decodeFile(imgFile.getAbsolutePath());
    		} else {
    			Toast.makeText(context, "文件不存在", Toast.LENGTH_SHORT).show();
    		}
    
    		return null;
    	}
    
    
    • 布局如下:
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    
        <ImageView
            android:id="@+id/img_external"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    
        <Button
            android:id="@+id/btn_external_save"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="BtnSaveImage"
            android:text="保存图片到SD卡" />
    
        <Button
            android:id="@+id/btn_external_delete"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="BtnDeleteImage"
            android:text="删除SD卡 图片" />
    
        <Button
            android:id="@+id/btn_external_read"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="BtnReadImage"
            android:text="显示SD卡 图片" />
    
    </LinearLayout>
    

    至此,本篇已结束,如有不对的地方,欢迎您的建议与指正。同时期待您的关注,感谢您的阅读,谢谢!

    微信关注公众号:  程序员Android,领福利

  • 相关阅读:
    产品经理职责
    Python基础知识之:字符串拼接
    Python基础知识之:hello world,注释,变量,数据类型
    Python初接触
    系统测试基础大纲
    编程零基础应当如何开始学习 Python?
    可以用 Python 编程语言做哪些神奇好玩的事情?
    江湖二三事:听说你想做数据分析师?
    “羊车门”问题
    用Turtle画正螺旋线
  • 原文地址:https://www.cnblogs.com/wangjie1990/p/11310901.html
Copyright © 2020-2023  润新知