android遍历SD卡所有图片,并生成缩略图(开机/插入SD卡自启动)

//Test_ListFile
package com.android;  

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

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;  
import android.os.Environment;

public class Test_ListFile extends ListActivity {  
     /** Called when the activity is first created. */  
     private String rootPath = "/sdcard";        //SD卡根目录
     private int j=0;                            //存放遍历图片的数量
     public final static int TASK_LOOP_COMPLETE = 0; 
     @Override  
     public void onCreate(Bundle savedInstanceState) {  
         super.onCreate(savedInstanceState);  
         setContentView(R.layout.main);   
         this.checksd();

     }

//检查SD卡状态,开始遍历图片
    public void checksd(){
        try{
    
String status = Environment.getExternalStorageState();      //获取SD卡状态
        //SD卡处于插入状态,并被机器识别
        if (status.equals(Environment.MEDIA_MOUNTED)) {
       
File sd=Environment.getExternalStorageDirectory();
            String path=sd.getPath()+"/picshow";
            File file=new File(path);
            if(!file.exists())
            file.mkdir();                                            //创建picshow文件夹,用于存放缩略图
            this.getFileDir(rootPath);                               //开始遍历SD卡所有图片
            //完成任务,弹出对话框,退出程序
           new AlertDialog.Builder(this).setTitle("通知").setMessage("共遍历图片"+j+"张").setPositiveButton("退出",new DialogInterface.OnClickListener() {
     

@Override
     
public void onClick(DialogInterface dialog, int which) {
     
// TODO Auto-generated method stub
     
finish();
     
System.exit(0);
     
}
             
}).show();
        }
        //SD卡未插入,或已被移除
        else if (status.equals(Environment.MEDIA_REMOVED)||status.equals(Environment.MEDIA_BAD_REMOVAL)){
       
new AlertDialog.Builder(this).setTitle("警告").setMessage("SD卡未被插入").setPositiveButton("关闭",new DialogInterface.OnClickListener() {
       

@Override

public void onClick(DialogInterface dialog, int which) {

// TODO Auto-generated method stub

finish();

}
       
}).show();
       }
       //正在检查SD卡
       else if(status.equals(Environment.MEDIA_CHECKING)){
        
Thread.sleep(500);                                   //延迟
        
status = Environment.getExternalStorageState();      //继续获取SD卡状态
        
this.checksd();                                      //重新调用checksd()
       }
       //SD卡不被识别
       else {
          
new AlertDialog.Builder(this).setTitle("警告").setMessage("SD卡不正确").setPositiveButton("关闭",new DialogInterface.OnClickListener() {
          

@Override
   
public void onClick(DialogInterface dialog, int which) {
   
// TODO Auto-generated method stub
   
finish();
   
System.exit(0);
   
}
          
}).show();
          }
        }catch(Exception ex){  
            ex.printStackTrace();  
        }
    

    }


        //产生缩略图  
        public Bitmap zoomImage(Bitmap bgimage, int newWidth, int newHeight) {  
    
int width = bgimage.getWidth();  
    
int height = bgimage.getHeight(); 
    
Matrix matrix = new Matrix();
    
float scaleWidth = ((float) newWidth) / width;  
    
float scaleHeight = ((float) newHeight) / height;
    
matrix.postScale(scaleWidth, scaleHeight);  
    
Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, width, height,  
    
matrix, true);  
    
return bitmap;  
    


       //储存缩略图
        public void saveFile(File file,String filepath)
       { 
         BitmapFactory.Options options = new BitmapFactory.Options();
         options.inJustDecodeBounds = true;
         Bitmap bitmap = BitmapFactory.decodeFile(filepath, options); 
         options.inJustDecodeBounds = false;                       
         int be = (int)(options.outHeight / (float)200);
         if (be <= 0)
         be = 1;
         options.inSampleSize = be;
         bitmap=BitmapFactory.decodeFile(filepath,options);
         bitmap=zoomImage(bitmap,200,200);
         File filex=new File("/sdcard/picshow/"+"pic_"+file.getName());
         try {
         FileOutputStream out=new FileOutputStream(filex);
         if(bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)){
         out.flush();
         out.close();
         }
         } catch (FileNotFoundException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
         } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
         }
     }

     //遍历SD卡所有图片
     public void getFileDir(String filePath) {  
         try{  
             File f = new File(filePath);  
             File[] files = f.listFiles();
             if(files != null){  
                 int count = files.length;
                 for (int i = 0; i < count; i++) {  
                     File file = files
                     String filepath  = file.getAbsolutePath();
                     String path=file.getPath();
                     //除存放缩略图的picshow文件夹,和系统自动生成的dcim文件夹外
                     if(filepath.endsWith("picshow")||filepath.endsWith("DCIM")) continue;

if(filepath.endsWith("jpg")||filepath.endsWith("gif")||filepath.endsWith("bmp")||filepath.endsWith("png"))
                     {
                    
j++;                       //每获取一张图片,j加1
                    
saveFile(file,filepath);   //存放图片
                    

                     }
                    //非图片文件
                    else 
                    {    //目标为文件夹,进入该文件夹继续遍历
                
if(file.isDirectory()){  
                             this.getFileDir(path);} 
                    }
                     continue;
                   }  
             } 
           }catch(Exception ex){  
             ex.printStackTrace();  
         }
     }


//开机自启动程序源代码
package com.android;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class root extends BroadcastReceiver { 
    public void onReceive(Context ctx, Intent intent) {  
        Log.d("BootReceiver", "system boot completed"); 
        String action="android.intent.action.MAIN";  
        String category="android.intent.category.LAUNCHER";
        Intent myi=new Intent(ctx,Test_ListFile.class);  
        myi.setAction(action);  
        myi.addCategory(category);  
        myi.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ctx.startActivity(myi);
        Intent s=new Intent(ctx,Test_ListFile.class);
        ctx.startService(s); 
    }  


//监听SD卡,插入SD卡启动程序
package com.android;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class sdcardboot extends BroadcastReceiver {  

    public void onReceive(Context context, Intent intent) {  
    
String action = intent.getAction();
        if (Intent.ACTION_MEDIA_MOUNTED.equals(action))
        {
        
Intent myi=new Intent(context,Test_ListFile.class); 
        
myi.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        
context.startActivity(myi);
        
Intent s=new Intent(context,Test_ListFile.class);
                context.startService(s); 
        }
    }  
}  


//AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.android"
      android:versionCode="1"
      android:versionName="1.0">
      <uses-sdk android:minSdkVersion="8" />
      <!--往sdcard中写入数据的权限 -->
      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
      <!--在sdcard中创建/删除文件的权限 -->
      <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>
      <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Test_ListFile"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

<receiver android:name=".root">  
        <intent-filter>  
            <action android:name="android.intent.action.BOOT_COMPLETED"/>  
            <category android:name="android.intent.category.HOME" />  
        </intent-filter>  
        </receiver>
        <receiver android:name=".sdcardboot" android:label="@string/app_name">  
          <intent-filter>  
            <action android:name="android.intent.action.MEDIA_EJECT"></action>  
            <action android:name="android.intent.action.MEDIA_REMOVED"></action>  
            <action android:name="android.intent.action.MEDIA_BAD_REMOVAL"></action>   
            <action android:name="android.intent.action.MEDIA_UNMOUNTED"></action>  
            <action android:name="android.intent.action.MEDIA_MOUNTED"></action> 
            <data android:scheme="file"></data>   
         </intent-filter>    
      </receiver> 
    </application>
</manifest>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个简单的实现示例: ``` public Map<String, List<File>> findPicturesByApp(Context context) { Map<String, List<File>> picturesByApp = new HashMap<>(); // 从外部存储器获取SD卡目录 File sdCardDirectory = Environment.getExternalStorageDirectory(); // 遍历SD卡目录 File[] files = sdCardDirectory.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) { // 如果是目录,则递归遍历子目录 findPicturesByAppInDirectory(context, file, picturesByApp); } else if (isPictureFile(file)) { // 如果是图片文件,则将其添加到Map中 String appName = getAppNameByPackageName(context, getPackageNameByFilePath(file.getAbsolutePath())); String key = appName + "图片"; if (!picturesByApp.containsKey(key)) { picturesByApp.put(key, new ArrayList<File>()); } picturesByApp.get(key).add(file); } } } return picturesByApp; } private void findPicturesByAppInDirectory(Context context, File directory, Map<String, List<File>> picturesByApp) { File[] files = directory.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) { findPicturesByAppInDirectory(context, file, picturesByApp); } else if (isPictureFile(file)) { String appName = getAppNameByPackageName(context, getPackageNameByFilePath(file.getAbsolutePath())); String key = appName + "图片"; if (!picturesByApp.containsKey(key)) { picturesByApp.put(key, new ArrayList<File>()); } picturesByApp.get(key).add(file); } } } } private boolean isPictureFile(File file) { String name = file.getName(); return name.endsWith(".jpg") || name.endsWith(".jpeg") || name.endsWith(".png") || name.endsWith(".gif"); } private String getPackageNameByFilePath(String filePath) { PackageManager pm = context.getPackageManager(); List<PackageInfo> packages = pm.getInstalledPackages(PackageManager.GET_ACTIVITIES); for (PackageInfo packageInfo : packages) { String packagePath = packageInfo.applicationInfo.sourceDir; if (filePath.startsWith(packagePath)) { return packageInfo.packageName; } } return null; } private String getAppNameByPackageName(Context context, String packageName) { PackageManager pm = context.getPackageManager(); ApplicationInfo appInfo = null; try { appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } if (appInfo != null) { return pm.getApplicationLabel(appInfo).toString(); } return null; } ``` 注释详细,可根据需要进行修改。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值