Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android通過ContentPrivider掃描sd卡所有圖片,並顯示

android通過ContentPrivider掃描sd卡所有圖片,並顯示

編輯:關於Android編程

如題:

重點在於ContentPrivider的使用,和圖片的顯示上

首先在使用ContentPrivider查找圖片前,先將sd卡整個掃描一遍,要不然的話你可能剛剛添加的圖片是不會查找出來的。


[html] view plaincopyprint?
// 必須在查找前進行全盤的掃描,否則新加入的圖片是無法得到顯示的(加入對sd卡操作的權限) 
    public void allScan() { 
        sendBroadcast(new Intent( 
                Intent.ACTION_MEDIA_MOUNTED, 
                Uri.parse("file://" + Environment.getExternalStorageDirectory()))); 
    } 

// 必須在查找前進行全盤的掃描,否則新加入的圖片是無法得到顯示的(加入對sd卡操作的權限)
 public void allScan() {
  sendBroadcast(new Intent(
    Intent.ACTION_MEDIA_MOUNTED,
    Uri.parse("file://" + Environment.getExternalStorageDirectory())));
 }加入對sd卡訪問的權限:


[html] view plaincopyprint?
<uses-permission android:name="android.permission.RESTART_PACKAGES" /> 
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

  <uses-permission android:name="android.permission.RESTART_PACKAGES" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
下一步就可以使用ContentPrivider了:


[html] view plaincopyprint?
/** 
 * @FILE:ImageService.java 
 * @AUTHOR:hui-ye 
 * @DATE:2013-5-21 下午3:30:41 
 **/ 
package com.image.service; 
 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 
 
import android.content.ContentResolver; 
import android.content.Context; 
import android.database.Cursor; 
import android.net.Uri; 
import android.provider.MediaStore; 
 
/******************************************* 
 *  
 * @CLASS:ImageService 
 * @DESCRIPTION: 
 * @AUTHOR:hui-ye 
 * @VERSION:v1.0 
 * @DATE:2013-5-21 下午3:30:41 
 *******************************************/ 
public class ImageService { 
    private Context context; 
 
    public ImageService(Context context) { 
        this.context = context; 
    } 
 
    /** 
     * @description:通過contentprovider獲得sd卡上的圖片 
     * @author:hui-ye 
     * @return:void 
     */ 
 
    public List<HashMap<String, String>> getImages() { 
        // 指定要查詢的uri資源 
        Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; 
        // 獲取ContentResolver 
        ContentResolver contentResolver = context.getContentResolver(); 
        // 查詢的字段 
        String[] projection = { MediaStore.Images.Media._ID, 
                MediaStore.Images.Media.DISPLAY_NAME, 
                MediaStore.Images.Media.DATA, MediaStore.Images.Media.SIZE }; 
        // 條件 
        String selection = MediaStore.Images.Media.MIME_TYPE + "=?"; 
        // 條件值(這裡的參數不是圖片的格式,而是標准,所有不要改動) 
        String[] selectionArgs = { "image/jpeg" }; 
        // 排序 
        String sortOrder = MediaStore.Images.Media.DATE_MODIFIED + " desc"; 
        // 查詢sd卡上的圖片 
        Cursor cursor = contentResolver.query(uri, projection, selection, 
                selectionArgs, sortOrder); 
        List<HashMap<String, String>> imageList = new ArrayList<HashMap<String, String>>(); 
        if (cursor != null) { 
            HashMap<String, String> imageMap = null; 
            cursor.moveToFirst(); 
            while (cursor.moveToNext()) { 
                imageMap = new HashMap<String, String>(); 
                // 獲得圖片的id 
                imageMap.put("imageID", cursor.getString(cursor 
                        .getColumnIndex(MediaStore.Images.Media._ID))); 
                // 獲得圖片顯示的名稱 
                imageMap.put("imageName", cursor.getString(cursor 
                        .getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME))); 
                // 獲得圖片的信息 
                imageMap.put( 
                        "imageInfo", 
                        "" 
                                + cursor.getLong(cursor 
                                        .getColumnIndex(MediaStore.Images.Media.SIZE) / 1024) 
                                + "kb"); 
                // 獲得圖片所在的路徑(可以使用路徑構建URI) 
                imageMap.put("data", cursor.getString(cursor 
                        .getColumnIndex(MediaStore.Images.Media.DATA))); 
                imageList.add(imageMap); 
            } 
            // 關閉cursor 
            cursor.close(); 
        } 
        return imageList; 
    } 

/**
 * @FILE:ImageService.java
 * @AUTHOR:hui-ye
 * @DATE:2013-5-21 下午3:30:41
 **/
package com.image.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

/*******************************************
 *
 * @CLASS:ImageService
 * @DESCRIPTION:
 * @AUTHOR:hui-ye
 * @VERSION:v1.0
 * @DATE:2013-5-21 下午3:30:41
 *******************************************/
public class ImageService {
 private Context context;

 public ImageService(Context context) {
  this.context = context;
 }

 /**
  * @description:通過contentprovider獲得sd卡上的圖片
  * @author:hui-ye
  * @return:void
  */

 public List<HashMap<String, String>> getImages() {
  // 指定要查詢的uri資源
  Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
  // 獲取ContentResolver
  ContentResolver contentResolver = context.getContentResolver();
  // 查詢的字段
  String[] projection = { MediaStore.Images.Media._ID,
    MediaStore.Images.Media.DISPLAY_NAME,
    MediaStore.Images.Media.DATA, MediaStore.Images.Media.SIZE };
  // 條件
  String selection = MediaStore.Images.Media.MIME_TYPE + "=?";
  // 條件值(這裡的參數不是圖片的格式,而是標准,所有不要改動)
  String[] selectionArgs = { "image/jpeg" };
  // 排序
  String sortOrder = MediaStore.Images.Media.DATE_MODIFIED + " desc";
  // 查詢sd卡上的圖片
  Cursor cursor = contentResolver.query(uri, projection, selection,
    selectionArgs, sortOrder);
  List<HashMap<String, String>> imageList = new ArrayList<HashMap<String, String>>();
  if (cursor != null) {
   HashMap<String, String> imageMap = null;
   cursor.moveToFirst();
   while (cursor.moveToNext()) {
    imageMap = new HashMap<String, String>();
    // 獲得圖片的id
    imageMap.put("imageID", cursor.getString(cursor
      .getColumnIndex(MediaStore.Images.Media._ID)));
    // 獲得圖片顯示的名稱
    imageMap.put("imageName", cursor.getString(cursor
      .getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME)));
    // 獲得圖片的信息
    imageMap.put(
      "imageInfo",
      ""
        + cursor.getLong(cursor
          .getColumnIndex(MediaStore.Images.Media.SIZE) / 1024)
        + "kb");
    // 獲得圖片所在的路徑(可以使用路徑構建URI)
    imageMap.put("data", cursor.getString(cursor
      .getColumnIndex(MediaStore.Images.Media.DATA)));
    imageList.add(imageMap);
   }
   // 關閉cursor
   cursor.close();
  }
  return imageList;
 }
}

我們將圖片信息全部放入到一個List<Map>中。

再下一步:

在activity中調用service獲得List<Map>,並用自定義的適配器顯示在listview中


[html] view plaincopyprint?
package com.image.imageview; 
 
import java.util.HashMap; 
import java.util.List; 
 
import android.app.Activity; 
import android.content.Context; 
import android.content.Intent; 
import android.net.Uri; 
import android.os.Bundle; 
import android.os.Environment; 
import android.view.LayoutInflater; 
import android.view.Menu; 
import android.view.View; 
import android.view.ViewGroup; 
import android.view.ViewGroup.LayoutParams; 
import android.widget.BaseAdapter; 
import android.widget.ImageView; 
import android.widget.LinearLayout; 
import android.widget.ListView; 
import android.widget.TextView; 
import android.widget.Toast; 
 
import com.image.service.ImageService; 
 
public class MainActivity extends Activity { 
    private ImageService imageService; 
    private List<HashMap<String, String>> images; 
 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_main); 
        imageService = new ImageService(this); 
        allScan(); 
        // 獲得所有的圖片 
        images = imageService.getImages(); 
        if (images.size() > 0) { 
            // 將所有的圖片顯示在listview中 
            ListView listview = (ListView) this.findViewById(R.id.listview); 
            Myadapter adapter = new Myadapter(this); 
            listview.setAdapter(adapter); 
        } else { 
            Toast.makeText(this, R.string.no_image, 1).show(); 
        } 
 
    } 
 
    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
        getMenuInflater().inflate(R.menu.main, menu); 
        return true; 
    } 
 
    // 必須在查找前進行全盤的掃描,否則新加入的圖片是無法得到顯示的(加入對sd卡操作的權限) 
    public void allScan() { 
        sendBroadcast(new Intent( 
                Intent.ACTION_MEDIA_MOUNTED, 
                Uri.parse("file://" + Environment.getExternalStorageDirectory()))); 
    } 
 
    /** 
     * @CLASS:Myadapter 
     * @DESCRIPTION:一個自定義的適配器 
     * @AUTHOR:hui-ye 
     * @VERSION:v1.0 
     * @DATE:2013-5-27 上午9:08:43 
     */ 
 
    class Myadapter extends BaseAdapter { 
        private LayoutInflater inflater; 
 
        public Myadapter(Context context) { 
            this.inflater = LayoutInflater.from(context); 
        } 
 
        @Override 
        public int getCount() { 
            return images.size(); 
        } 
 
        @Override 
        public Object getItem(int position) { 
            return position; 
        } 
 
        @Override 
        public long getItemId(int position) { 
            return position; 
        } 
 
        @Override 
        public View getView(int position, View view, ViewGroup parent) { 
            ViewHolder holder = null; 
            if (view == null) { 
                holder = new ViewHolder(); 
                // 獲取行布局,對行布局中的控件進行設置賦值 
                view = inflater.inflate(R.layout.item, null); 
                holder.imageName = (TextView) view.findViewById(R.id.name); 
                holder.imageInfo = (TextView) view.findViewById(R.id.size); 
                holder.image = (ImageView) view.findViewById(R.id.image); 
                view.setTag(holder); 
            } else { 
                holder = (ViewHolder) view.getTag(); 
            } 
            holder.imageName.setText(images.get(position).get("imageName")); 
            holder.imageInfo.setText(images.get(position).get("imageInfo")); 
            String path = images.get(position).get("data"); 
            // 注意這裡uri的使用,可以直接使用uri地址來構建一個image圖片 
            Uri uri = Uri.parse(path); 
            // 給imageview設置圖片 
            holder.image.setImageURI(uri); 
            return view; 
        } 
 
    } 
 
    class ViewHolder { 
        private TextView imageName; 
        private TextView imageInfo; 
        private ImageView image; 
    } 

package com.image.imageview;

import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.image.service.ImageService;

public class MainActivity extends Activity {
 private ImageService imageService;
 private List<HashMap<String, String>> images;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  imageService = new ImageService(this);
  allScan();
  // 獲得所有的圖片
  images = imageService.getImages();
  if (images.size() > 0) {
   // 將所有的圖片顯示在listview中
   ListView listview = (ListView) this.findViewById(R.id.listview);
   Myadapter adapter = new Myadapter(this);
   listview.setAdapter(adapter);
  } else {
   Toast.makeText(this, R.string.no_image, 1).show();
  }

 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

 // 必須在查找前進行全盤的掃描,否則新加入的圖片是無法得到顯示的(加入對sd卡操作的權限)
 public void allScan() {
  sendBroadcast(new Intent(
    Intent.ACTION_MEDIA_MOUNTED,
    Uri.parse("file://" + Environment.getExternalStorageDirectory())));
 }

 /**
  * @CLASS:Myadapter
  * @DESCRIPTION:一個自定義的適配器
  * @AUTHOR:hui-ye
  * @VERSION:v1.0
  * @DATE:2013-5-27 上午9:08:43
  */

 class Myadapter extends BaseAdapter {
  private LayoutInflater inflater;

  public Myadapter(Context context) {
   this.inflater = LayoutInflater.from(context);
  }

  @Override
  public int getCount() {
   return images.size();
  }

  @Override
  public Object getItem(int position) {
   return position;
  }

  @Override
  public long getItemId(int position) {
   return position;
  }

  @Override
  public View getView(int position, View view, ViewGroup parent) {
   ViewHolder holder = null;
   if (view == null) {
    holder = new ViewHolder();
    // 獲取行布局,對行布局中的控件進行設置賦值
    view = inflater.inflate(R.layout.item, null);
    holder.imageName = (TextView) view.findViewById(R.id.name);
    holder.imageInfo = (TextView) view.findViewById(R.id.size);
    holder.image = (ImageView) view.findViewById(R.id.image);
    view.setTag(holder);
   } else {
    holder = (ViewHolder) view.getTag();
   }
   holder.imageName.setText(images.get(position).get("imageName"));
   holder.imageInfo.setText(images.get(position).get("imageInfo"));
   String path = images.get(position).get("data");
   // 注意這裡uri的使用,可以直接使用uri地址來構建一個image圖片
   Uri uri = Uri.parse(path);
   // 給imageview設置圖片
   holder.image.setImageURI(uri);
   return view;
  }

 }

 class ViewHolder {
  private TextView imageName;
  private TextView imageInfo;
  private ImageView image;
 }
}

最後貼出主頁面布局文件[html] view plaincopyprint?
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    tools:context=".MainActivity" > 
 
    <LinearLayout 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:orientation="horizontal" > 
 
        <TextView 
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            android:layout_weight="1" 
            android:text="@string/imagename" /> 
 
        <TextView 
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            android:layout_weight="1" 
            android:text="@string/imageinfo" /> 
 
        <TextView 
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            android:layout_weight="1" 
            android:text="@string/image" /> 
    </LinearLayout> 
 
    <LinearLayout 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" 
        android:orientation="vertical" > 
 
        <ListView 
            android:id="@+id/listview" 
            android:layout_width="fill_parent" 
            android:layout_height="fill_parent" /> 
    </LinearLayout> 
 
</LinearLayout> 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/imagename" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/imageinfo" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/image" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <ListView
            android:id="@+id/listview"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />
    </LinearLayout>

</LinearLayout>
listview的行布局文件


[html] view plaincopyprint?
<?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="20dp" 
    android:orientation="horizontal"  
    > 
 
    <TextView 
        android:id="@+id/name" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:maxLines="1" 
        android:layout_weight="1"  
        android:ellipsize="end"/> 
 
    <TextView 
        android:id="@+id/size" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:maxLines="1" 
        android:layout_weight="1" 
         /> 
 
    <ImageView 
        android:id="@+id/image" 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" 
        android:layout_weight="1" 
        /> 
 
</LinearLayout> 

<?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="20dp"
    android:orientation="horizontal"
    >

    <TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:layout_weight="1"
        android:ellipsize="end"/>

    <TextView
        android:id="@+id/size"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:layout_weight="1"
         />

    <ImageView
        android:id="@+id/image"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        />

</LinearLayout>
至此完成。重點還是在ContentPrivider的使用,和listview的適配器的生成,圖片的顯示直接使用image.setImageURI(uri);上

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved