Android文件管理器

零、前言

因项目需要自己写了一个文件管理器,主要实现的功能有以下几点:

  • 获取设备中的图片、音乐、视频、文档文件;
  • 刷新查看最新文件;
  • 选中文件并发送;
    技术要点如下:
  • 异步读取文件:耗时操作在非主线程中读取
  • 回调返回文件列表 :FileService读取文件完成自动返回list
  • 主动刷新文件:点击刷新按钮,service重新读取文件

一、代码结构设计

流程图
时序图设计

二、布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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:background="@drawable/background7"
    android:fitsSystemWindows="true"
    >

    <LinearLayout
        android:id="@+id/ll_toplist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/plum1"
        android:orientation="horizontal"
        >

        <ImageView
            android:id="@+id/iv_return"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/ic_keyboard_arrow_left_40dp"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="@string/back_main_page"
            android:textColor="@color/black"
            android:textSize="18dp"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="100dp"
            android:text="@string/choose_file"
            android:textColor="@color/black"
            android:textSize="20dp"
            ></TextView>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            >

            <ImageView
                android:id="@+id/iv_refresh"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:background="@drawable/ic_refresh_blue_200_36dp"
                android:gravity="center"
                />
        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/ll_btngroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/ll_toplist"
        android:orientation="horizontal"
        >

        <Button
            android:id="@+id/btn_jpg"
            style="@style/style_file_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@color/common_blue"
            android:gravity="center"
            android:text="@string/str_picture"
            android:textSize="16dp"
            android:textStyle="bold"
            />

        <Button
            android:id="@+id/btn_music"
            style="@style/style_file_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@color/common_blue"
            android:gravity="center"
            android:text="@string/str_music"
            android:textSize="16dp"
            android:textStyle="bold"
            />

        <Button
            android:id="@+id/btn_movie"
            style="@style/style_file_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@color/common_blue"
            android:gravity="center"
            android:text="@string/str_movie"
            android:textSize="16dp"
            android:textStyle="bold"
            />

        <Button
            android:id="@+id/btn_doc"
            style="@style/style_file_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@color/common_blue"
            android:gravity="center"
            android:text="@string/str_document"
            android:textSize="16dp"
            android:textStyle="bold"
            />
    </LinearLayout>


    <Button
        android:id="@+id/btn_send"
        style="@style/style_file_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="15dp"
        android:background="@drawable/bg_cancel_btn"
        android:gravity="center"
        android:text="@string/str_send"

        />

    <ListView
        android:id="@+id/lv_file"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/btn_send"
        android:layout_below="@+id/ll_btngroup"
        android:choiceMode="singleChoice"
        android:listSelector="@drawable/listviewselector"
        >

    </ListView>


</RelativeLayout>

在这里插入图片描述

还有一个dialog忽略

三、关键activity和service

附上关键的activity和service,其他的Adaper和bean文件忽略

package com.example.colorfulquicklytransmission.ui.activity;


import android.annotation.SuppressLint;
import android.os.Bundle;

import com.example.colorfulquicklytransmission.R;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.colorfulquicklytransmission.data.bean.Documentbean;
import com.example.colorfulquicklytransmission.data.bean.Moviebean;
import com.example.colorfulquicklytransmission.data.bean.Musicbean;
import com.example.colorfulquicklytransmission.data.bean.Picturebean;
import com.example.colorfulquicklytransmission.service.file.FileService;
import com.example.colorfulquicklytransmission.ui.adapter.DocumentAdapter;
import com.example.colorfulquicklytransmission.ui.adapter.MovieAdapter;
import com.example.colorfulquicklytransmission.ui.adapter.MusicAdapter;
import com.example.colorfulquicklytransmission.ui.adapter.PictureAdapter;
import com.example.colorfulquicklytransmission.ui.dialog.ConfirmDialog;


import java.util.ArrayList;
import java.util.List;

/**
 * Created by PsycheWang on 2021/11/9.
 */
public class FileManageActivity extends Activity implements View.OnClickListener {
    private static final String TAG = "FileManageActivity";
    private static final int FILE_READ_MESSAGE = 1;
    private static final int FILE_READOK_MESSAGE = 2;
    public static final int FILE_MUISC = 3;
    public static final int FILE_MOVIE = 4;
    public static final int FILE_PICTURE = 5;
    public static final int FILE_DOCUMENT = 6;


    Button mBtndoc, mBtnjpg, mBtnmusic, mBtnmovie, mBtnSend;
    ListView mlvFile;
    ImageView mIvreturn, mIvreflesh;


    private String mFileName = null;
    private String mFilePath = null;
    private int mFileType = FILE_MUISC;
    private List<Musicbean> mMusiclist = new ArrayList<>();
    private List<Moviebean> mMovielist = new ArrayList<>();
    private List<Picturebean> mPicturelist = new ArrayList<>();
    private List<Documentbean> mDocumentList = new ArrayList<>();


    FileService.MyBinder myBinder;
    Context mContext;
    PictureAdapter mPictureAdapter;
    MusicAdapter mMusicAdapter;
    MovieAdapter mMovieAdapter;
    DocumentAdapter mDocumentAdapter;

    ConfirmDialog confirmDialog;


    public FileServiceCallBack fileServiceCallBack = new FileServiceCallBack() {
        @Override
        public void onFileReadState(boolean state) {
            Message message = mHandler.obtainMessage();
            if (state) {
                message.what = FILE_READ_MESSAGE;
                mHandler.sendMessage(message);
            } else {
                message.what = FILE_READOK_MESSAGE;
                mHandler.sendMessage(message);
                Log.d(TAG, "isgetFile: 加载结束");
            }
        }

        @Override
        public void onMusicFileGet(List<Musicbean> musicbeanlist) {
            if (musicbeanlist != null) {
                mHandler.obtainMessage(FILE_MUISC, musicbeanlist).sendToTarget();
            } else {
                Log.d(TAG, "onMusicFileGet: musicbeanlist is empty");
            }
        }

        @Override
        public void onMovieFileGet(List<Moviebean> moviebeanlist) {
            if (moviebeanlist != null) {
                mHandler.obtainMessage(FILE_MOVIE, moviebeanlist).sendToTarget();
            } else {
                Log.d(TAG, "onMovieFileGet: moviebeanlist is empty");
            }
        }

        @Override
        public void onPictureFileGet(List<Picturebean> picturebeanlist) {
            if (picturebeanlist != null) {
                mHandler.obtainMessage(FILE_PICTURE, picturebeanlist).sendToTarget();
            } else {
                Log.d(TAG, "onPictureFileGet: picturebeanlist is empty");
            }
        }

        @Override
        public void onDocumentFileGet(List<Documentbean> documentbeanlist) {
            if (documentbeanlist != null) {
                mHandler.obtainMessage(FILE_DOCUMENT, documentbeanlist).sendToTarget();
            } else {
                Log.d(TAG, "onDocumentFileGet: documentbeanlist is empty");
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_file);
        initView();
        setListener();
        mContext = this;
        final Intent intent = new Intent(this, FileService.class);
        bindService(intent, connection, BIND_AUTO_CREATE);
    }

    public Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case FILE_READ_MESSAGE:
                    Toast.makeText(mContext, getResources().getString(R.string.toast_get_file), Toast.LENGTH_SHORT).show();
                    break;
                case FILE_READOK_MESSAGE:
                    Toast.makeText(mContext, getResources().getString(R.string.toast_get_file_success), Toast.LENGTH_SHORT).show();
                    onClick(mBtnmusic);
                    break;
                case FILE_MUISC:
                    List<Musicbean> musicList = (List<Musicbean>) msg.obj;
                    mMusiclist.clear();
                    mMusiclist.addAll(musicList);
                    mMusicAdapter = new MusicAdapter(mContext, mMusiclist);
                    break;
                case FILE_MOVIE:
                    List<Moviebean> movieList = (List<Moviebean>) msg.obj;
                    mMovielist.clear();
                    mMovielist.addAll(movieList);
                    mMovieAdapter = new MovieAdapter(mContext, mMovielist);
                    break;
                case FILE_PICTURE:
                    List<Picturebean> pictureList = (List<Picturebean>) msg.obj;
                    mPicturelist.clear();
                    mPicturelist.addAll(pictureList);
                    mPictureAdapter = new PictureAdapter(mContext, mPicturelist);
                    break;
                case FILE_DOCUMENT:
                    List<Documentbean> documentList = (List<Documentbean>) msg.obj;
                    mDocumentList.clear();
                    mDocumentList.addAll(documentList);
                    mDocumentAdapter = new DocumentAdapter(mContext, mDocumentList);
                    break;
                default:
                    break;
            }
        }
    };

    ServiceConnection connection = new ServiceConnection() {
        @SuppressLint("ResourceAsColor")
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            myBinder = (FileService.MyBinder) iBinder;
            if (myBinder != null) {
                myBinder.setCallBack(fileServiceCallBack);
                myBinder.init();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mPictureAdapter.release();
            if (myBinder != null) {
                fileServiceCallBack = null;
            }
        }
    };

    private void initView() {
        mBtndoc = findViewById(R.id.btn_doc);
        mBtnjpg = findViewById(R.id.btn_jpg);
        mBtnmovie = findViewById(R.id.btn_movie);
        mBtnmusic = findViewById(R.id.btn_music);
        mlvFile = findViewById(R.id.lv_file);
        mIvreturn = findViewById(R.id.iv_return);
        mBtnSend = findViewById(R.id.btn_send);
        mIvreflesh = findViewById(R.id.iv_refresh);
        mBtndoc.setOnClickListener(this);
        mBtnjpg.setOnClickListener(this);
        mBtnmovie.setOnClickListener(this);
        mBtnmusic.setOnClickListener(this);
        mIvreturn.setOnClickListener(this);
        mBtnSend.setOnClickListener(this);
        mIvreflesh.setOnClickListener(this);
    }

    private void setListener() {
        //给listview设置item的点击监听
        mlvFile.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                TextView tvFileName = (TextView) view.findViewById(R.id.tv_name);
                mFileName = tvFileName.getText().toString();
                TextView tvFilePath = (TextView) view.findViewById(R.id.tv_path);
                mFilePath = tvFilePath.getText().toString();
            }
        });
    }

    @SuppressLint("ResourceAsColor")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_jpg:
                mlvFile.setAdapter(mPictureAdapter);
                mPictureAdapter.notifyDataSetChanged();
                mFileType = FILE_PICTURE;
                mBtnjpg.setBackgroundColor(R.color.sakura2);
                mBtnmovie.setBackgroundColor(R.color.common_blue);
                mBtndoc.setBackgroundColor(R.color.common_blue);
                mBtnmusic.setBackgroundColor(R.color.common_blue);
                break;
            case R.id.btn_music:

                mlvFile.setAdapter(mMusicAdapter);
                mMusicAdapter.notifyDataSetChanged();
                mFileType = FILE_MUISC;
                mBtnmovie.setBackgroundColor(R.color.common_blue);
                mBtndoc.setBackgroundColor(R.color.common_blue);
                mBtnjpg.setBackgroundColor(R.color.common_blue);
                mBtnmusic.setBackgroundColor(R.color.sakura2);
                break;
            case R.id.btn_movie:

                mlvFile.setAdapter(mMovieAdapter);
                mMovieAdapter.notifyDataSetChanged();
                mFileType = FILE_MOVIE;
                mBtnjpg.setBackgroundColor(R.color.common_blue);
                mBtndoc.setBackgroundColor(R.color.common_blue);
                mBtnmusic.setBackgroundColor(R.color.common_blue);
                mBtnmovie.setBackgroundColor(R.color.sakura2);
                break;
            case R.id.btn_doc:
                mlvFile.setAdapter(mDocumentAdapter);
                mDocumentAdapter.notifyDataSetChanged();
                mFileType = FILE_DOCUMENT;
                mBtnmovie.setBackgroundColor(R.color.common_blue);
                mBtnjpg.setBackgroundColor(R.color.common_blue);
                mBtnmusic.setBackgroundColor(R.color.common_blue);
                mBtndoc.setBackgroundColor(R.color.sakura2);
                break;
            case R.id.iv_return:
                Intent intent = new Intent(FileManageActivity.this, FirstActivity.class);
                startActivity(intent);
                onDestroy();
                break;
            case R.id.btn_send:
                if (mFileName == null) {
                    Toast.makeText(mContext, getResources().getString(R.string.toast_choose_file), Toast.LENGTH_LONG).show();
                } else {
                    showMyDialog(getResources().getString(R.string.dialog_send_sure) + mFileName + getResources().getString(R.string.dialog_question_mark),
                            getResources().getString(R.string.dialog_sendfile_yes), getResources().getString(R.string.dialog_sendfile_no));
                }
                break;
            case R.id.iv_refresh:
                mlvFile.setAdapter(null);
                myBinder.init();
                mBtnjpg.setBackgroundColor(R.color.common_blue);
                mBtndoc.setBackgroundColor(R.color.common_blue);
                mBtnmusic.setBackgroundColor(R.color.common_blue);
                mBtnmovie.setBackgroundColor(R.color.common_blue);
            default:
                break;
        }
    }


    /**
     * 发送弹框提示,点击发送跳转到发送界面
     */
    public void showMyDialog(String title, String yesText, String noText) {

        confirmDialog = new ConfirmDialog(this, R.layout.dialog_send, title, yesText, noText);
        confirmDialog.show();
        //给弹框设置弹出的位置和大小
        Window dialogWindow = confirmDialog.getWindow();
        WindowManager.LayoutParams layoutParams = dialogWindow.getAttributes();
        layoutParams.width = 900;//设置弹框的宽度
        layoutParams.height = 900;//设置弹框的高度
        dialogWindow.setAttributes(layoutParams);
        confirmDialog.setConfirmDialogView(dialogWindow);
        confirmDialog.setOnButtonClickListener(new ConfirmDialog.OnClickBtnListener() {

            @Override
            public void onClickYes() {
                Log.d(TAG, "onClickYes: 点击确认发送");
                TransferActivity.actionStart(FileManageActivity.this, mFilePath, mFileType);
                //finish();
                Log.d(TAG, "onClickYes: 查看文件类型" + mFileType);

            }

            @Override
            public void onClickNo() {
                Log.d(TAG, "onClickNo: 点击取消发送 ");
            }
        });
    }

    @Override
    protected void onDestroy() {
        if (mPictureAdapter != null) {
            mPictureAdapter.release();
        }
        if (myBinder != null) {
            unbindService(connection);
        }
        fileServiceCallBack = null;
        super.onDestroy();
    }
}
package com.example.colorfulquicklytransmission.service.file;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.util.Log;

import com.example.colorfulquicklytransmission.R;
import com.example.colorfulquicklytransmission.data.bean.Documentbean;
import com.example.colorfulquicklytransmission.data.bean.Moviebean;
import com.example.colorfulquicklytransmission.data.bean.Musicbean;
import com.example.colorfulquicklytransmission.data.bean.Picturebean;
import com.example.colorfulquicklytransmission.ui.activity.FileServiceCallBack;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class FileService extends Service {

    private static final String TAG = "FileService";

    private static List<Musicbean> mMusicList = new ArrayList<>();
    private static List<Moviebean> mMovieList = new ArrayList<>();
    private static List<Picturebean> mPictureList = new ArrayList<>();
    private static List<Documentbean> mDocumentList = new ArrayList<>();
    private static FileServiceCallBack fileServiceCallBack;
    private static int INIT_FILE_FLAG = 1;
    Context context;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return new MyBinder();
    }

    public class MyBinder extends Binder {
        public void setCallBack(FileServiceCallBack fileServiceCallBack1) {
            Log.d(TAG, "setCallBack: " + fileServiceCallBack);
            fileServiceCallBack = fileServiceCallBack1;
        }

        public void init() {
            initFileData();
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
    }

    public void initFileData() {
        mMusicList.clear();
        initMusicData();

        mPictureList.clear();
        initPictureData();

        mDocumentList.clear();
        initDocumentData();

        mMovieList.clear();
        initMovieData();
    }


    public List<Musicbean> initMusicData() {
        Log.d(TAG, "run: " + fileServiceCallBack);
        Thread mThread = new Thread() {
            public void run() {
                super.run();
                if (fileServiceCallBack != null) {
                    fileServiceCallBack.onFileReadState(true);
                }
                mMusicList = readMusicData(context);
                if (fileServiceCallBack != null) {
                    INIT_FILE_FLAG++;
                    Log.d(TAG, "INIT_FILE_FLAG " + INIT_FILE_FLAG);
                    fileServiceCallBack.onMusicFileGet(mMusicList);
                    if (INIT_FILE_FLAG == 5) {
                        fileServiceCallBack.onFileReadState(false);
                        INIT_FILE_FLAG = 1;
                        Log.d(TAG, "initFileData: " + "读取完毕");
                    }
                }

            }
        };
        mThread.start();
        return mMusicList;
    }

    public List<Moviebean> initMovieData() {
        Thread mThread = new Thread() {
            public void run() {
                super.run();
                mMovieList = readMovieData(context);
                if (fileServiceCallBack != null) {
                    INIT_FILE_FLAG++;
                    Log.d(TAG, "INIT_FILE_FLAG " + INIT_FILE_FLAG);
                    fileServiceCallBack.onMovieFileGet(mMovieList);
                    if (INIT_FILE_FLAG == 5) {
                        fileServiceCallBack.onFileReadState(false);
                        Log.d(TAG, "initFileData: " + "读取完毕");
                        INIT_FILE_FLAG = 1;
                    }
                }
            }
        };
        mThread.start();
        return mMovieList;
    }

    public List<Picturebean> initPictureData() {
        Thread mThread = new Thread() {
            public void run() {
                super.run();
                try {
                    mPictureList = readPictureData(context);
                    if (fileServiceCallBack != null) {
                        INIT_FILE_FLAG++;
                        Log.d(TAG, "INIT_FILE_FLAG " + INIT_FILE_FLAG);
                        fileServiceCallBack.onPictureFileGet(mPictureList);
                        if (INIT_FILE_FLAG == 5) {
                            fileServiceCallBack.onFileReadState(false);
                            Log.d(TAG, "initFileData: " + "读取完毕");
                            INIT_FILE_FLAG = 1;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        mThread.start();
        return mPictureList;
    }

    public List<Documentbean> initDocumentData() {
        Thread mThread = new Thread() {
            public void run() {
                super.run();
                mDocumentList = readDocumentData(context);
                if (fileServiceCallBack != null) {
                    INIT_FILE_FLAG++;
                    Log.d(TAG, "INIT_FILE_FLAG " + INIT_FILE_FLAG);
                    fileServiceCallBack.onDocumentFileGet(mDocumentList);
                    if (INIT_FILE_FLAG == 5) {
                        fileServiceCallBack.onFileReadState(false);
                        Log.d(TAG, "initFileData: " + "读取完毕");
                        INIT_FILE_FLAG = 1;
                    }
                }
            }
        };
        mThread.start();
        return mDocumentList;
    }

    /**
     * 读取音乐
     */
    public static List<Musicbean> readMusicData(Context context) {
        Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null,
                null, MediaStore.Audio.AudioColumns.IS_MUSIC);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                Musicbean music = new Musicbean();
                music.setmMusicSong(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME)));
                music.setmMusicPath(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)));
                long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));
                music.setmMusicSize(getNetFileSizeDescription(size));
                long album_id = cursor.getInt(cursor
                        .getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
                long songid = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
                music.setmMusicBitmap(getMusicBitmap(context, songid, album_id));
                mMusicList.add(music);
            }
            cursor.close();
        }
        return mMusicList;
    }

    /**
     * 获取音乐专辑封面
     */
    public static Bitmap getMusicBitmap(Context context, long songid, long albumid) {
        Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
        Bitmap bm = null;
        try {
            if (albumid < 0) {
                Uri uri = Uri.parse("content://media/external/audio/media/"
                        + songid + "/albumart");
                ParcelFileDescriptor pfd = context.getContentResolver()
                        .openFileDescriptor(uri, "r");
                if (pfd != null) {
                    FileDescriptor fd = pfd.getFileDescriptor();
                    bm = BitmapFactory.decodeFileDescriptor(fd);
                }
            } else {
                Uri uri = ContentUris.withAppendedId(sArtworkUri, albumid);
                ParcelFileDescriptor pfd = context.getContentResolver()
                        .openFileDescriptor(uri, "r");
                if (pfd != null) {
                    FileDescriptor fd = pfd.getFileDescriptor();
                    bm = BitmapFactory.decodeFileDescriptor(fd);
                } else {
                    return null;
                }
            }
        } catch (FileNotFoundException ex) {
        }
        //如果获取的bitmap为空,则返回一个默认的bitmap
        if (bm == null) {
            Resources resources = context.getResources();
            Drawable drawable = resources.getDrawable(R.mipmap.icon_mp3);
            //Drawable 转 Bitmap
            BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            bm = bitmapDrawable.getBitmap();
        }
        return Bitmap.createScaledBitmap(bm, 150, 150, true);
    }


    /**
     * 读取视频
     */
    public static List<Moviebean> readMovieData(Context context) {
        Cursor cursor = context.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null,
                null, null, MediaStore.Video.Media.DISPLAY_NAME);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                Moviebean movie = new Moviebean();
                movie.setmMovieName(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME)));
                movie.setmMoviePath(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA)));
                long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
                movie.setmMovieSize(getNetFileSizeDescription(size));
                mMovieList.add(movie);
            }
            cursor.close();
        }
        return mMovieList;
    }


    /**
     * 读取图片
     */

    public static List<Picturebean> readPictureData(Context context) throws Exception {
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media.DATA},
                MediaStore.Images.ImageColumns.MIME_TYPE + "=? or "
                        + MediaStore.Images.ImageColumns.MIME_TYPE + "=?",
                new String[]{"image/jpeg", "image/png"},
                MediaStore.Images.ImageColumns.DATE_MODIFIED);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                Picturebean picture = new Picturebean();
                String picturePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
                picture.setmPicturePath(picturePath);
                File file = new File(picturePath);
                if (file.exists()) {
                    picture.setmPictureBitmap(BitmapFactory.decodeFile(picturePath));
                }
                picture.setmPictureName(picturePath.substring(picturePath.lastIndexOf("/") + 1));

                if (file.exists()) {
                    long size = 0;
                    FileInputStream fis = null;
                    fis = new FileInputStream(file);
                    size = fis.available();
                    picture.setmPictureSize(getNetFileSizeDescription(size));
                }
                mPictureList.add(picture);
            }
            cursor.close();
        }
        Log.d(TAG, "getPictureData: " + mPictureList.size());
        return mPictureList;
    }


    /**
     * 读取文件
     */
    @SuppressLint("Range")
    public static List<Documentbean> readDocumentData(Context context) {

        String selection = MediaStore.Files.FileColumns.MIME_TYPE + "= ? "
                + " or " + MediaStore.Files.FileColumns.MIME_TYPE + " = ? "
                + " or " + MediaStore.Files.FileColumns.MIME_TYPE + " = ? "
                + " or " + MediaStore.Files.FileColumns.MIME_TYPE + " = ? ";

        String[] selectionArgs = new String[]{"text/plain", "application/pdf", "application/vnd.ms-powerpoint", "application/vnd.ms-excel"};


        Cursor cursor = context.getContentResolver().query(MediaStore.Files.getContentUri("external"),
                null, "mime_type=\"text/plain\"", null, null);

        if (cursor != null) {
            Log.d(TAG, "getDocumentData: " + cursor.getCount());
            while (cursor.moveToNext()) {
                Documentbean document = new Documentbean();
                document.setmDocumentName(cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.TITLE)));
                document.setmDocumentPath(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA)));
                long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.SIZE));
                document.setmDocumentSize(getNetFileSizeDescription(size));
                mDocumentList.add(document);
            }
            cursor.close();
        }
        Log.d(TAG, "getPictureData: " + mDocumentList.size());
        return mDocumentList;
    }

    /**
     * 文件大小转换函数,转换byte为KB,MB,GB
     */
    public static String getNetFileSizeDescription(long size) {
        StringBuffer bytes = new StringBuffer();
        DecimalFormat format = new DecimalFormat("###.0");
        if (size >= 1024 * 1024 * 1024) {
            double i = (size / (1024.0 * 1024.0 * 1024.0));
            bytes.append(format.format(i)).append("GB");
        } else if (size >= 1024 * 1024) {
            double i = (size / (1024.0 * 1024.0));
            bytes.append(format.format(i)).append("MB");
        } else if (size >= 1024) {
            double i = (size / (1024.0));
            bytes.append(format.format(i)).append("KB");
        } else if (size < 1024) {
            if (size <= 0) {
                bytes.append("0B");
            } else {
                bytes.append((int) size).append("B");
            }
        }
        return bytes.toString();
    }

}
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值