Android sd卡状态监听,文件搜索,媒体文件刷新


整理一下关于sd卡相关知识点,主要包括sd卡状态监听,sd卡文件搜索,sd卡媒体数据库(系统支持媒体类型)刷新模块:


一:sd卡状态进行监听

有时程序进行外部数据读取和写入时,为防止异常发生需要对sd卡状态进行监听,对于sd卡的状态我们可以采用注册广播来实现

下面是文档中一个经典例子;

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //监听sdcard状态广播  
  2.    BroadcastReceiver mExternalStorageReceiver;  
  3.    //sdcard可用状态  
  4.    boolean mExternalStorageAvailable = false;  
  5.    //sdcard可写状态  
  6.    boolean mExternalStorageWriteable = false;  
  7.   
  8.    void updateExternalStorageState() {  
  9.        //获取sdcard卡状态  
  10.        String state = Environment.getExternalStorageState();  
  11.        if (Environment.MEDIA_MOUNTED.equals(state)) {  
  12.            mExternalStorageAvailable = mExternalStorageWriteable = true;  
  13.        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {  
  14.            mExternalStorageAvailable = true;  
  15.            mExternalStorageWriteable = false;  
  16.        } else {  
  17.            mExternalStorageAvailable = mExternalStorageWriteable = false;  
  18.        }  
  19.          
  20.    }  
  21.    //开始监听  
  22.    void startWatchingExternalStorage() {  
  23.        mExternalStorageReceiver = new BroadcastReceiver() {  
  24.            @Override  
  25.            public void onReceive(Context context, Intent intent) {  
  26.                Log.i("test""Storage: " + intent.getData());  
  27.                updateExternalStorageState();  
  28.            }  
  29.        };  
  30.        IntentFilter filter = new IntentFilter();  
  31.        filter.addAction(Intent.ACTION_MEDIA_MOUNTED);  
  32.        filter.addAction(Intent.ACTION_MEDIA_REMOVED);  
  33.        registerReceiver(mExternalStorageReceiver, filter);  
  34.        updateExternalStorageState();  
  35.    }  
  36.    //停止监听  
  37.    void stopWatchingExternalStorage() {  
  38.        unregisterReceiver(mExternalStorageReceiver);  
  39.    }  


二:sdcard下搜索某一类型(通常是后缀名相同)文件,或是指定文件名的查找功能

(1)搜索指定文件

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public String searchFile(String filename){    
  2.     
  3.         String res="";    
  4.         File[] files=new File("/sdcard").listFiles();    
  5.         for(File f:files){    
  6.             if(f.isDirectory())    
  7.                 searchFile(f.getName());    
  8.             else    
  9.             if(f.getName().indexOf(filename)>=0)    
  10.                 res+=f.getPath()+"\n";    
  11.         }    
  12.         if(res.equals(""))    
  13.             res="file can't find!";    
  14.         return res;    
  15.     }    

(2)指定相同后缀名称文件类型

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. private List<String> files = new ArrayList<String>();    
  2.     
  3. class FindFilter implements FilenameFilter {    
  4.     public boolean accept(File dir, String name) {    
  5.         return (name.endsWith(".txt"));    
  6.     }    
  7. }    
  8.     
  9. public void updateList() {    
  10.      File home = new File("/sdcard/");    
  11.   if (home.listFiles( new FindFilter()).length > 0) {    
  12.       for (File file : home.listFiles( new FindFilter())) {    
  13.        files.add(file.getName());    
  14.    

三:媒体数据库的刷新,

当android的系统启动的时候,系统会自动扫描sdcard内的文件,并把获得的媒体文件信息保存在一个系统媒体数据库中,
程序想要访问多媒体文件,就可以直接访问媒体数据库中即可,而用直接去sdcard中取。
但是,如果系统在不重新启动情况下,媒体数据库信息是不会更新的,这里举个例子,当应用程序保存一张图片到本地后(已成功),
但打开系统图片库查看时候,你会发现图片库内并没有你刚刚保存的那张图片,原因就在于系统媒体库没有及时更新,这时就需要手动刷新文件系统了



方式一:发送一广播信息通知系统进行文件刷新

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. private void scanSdCard(){    
  2.            IntentFilter intentfilter = new IntentFilter(Intent.ACTION_MEDIA_SCANNER_STARTED);    
  3.            intentfilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);    
  4.            intentfilter.addDataScheme("file");            
  5.            registerReceiver(scanSdReceiver, intentfilter);    
  6.            Intent intent = new Intent();    
  7.            intent.setAction(Intent.ACTION_MEDIA_MOUNTED);    
  8.            intent.setData(Uri.parse("file://" + Environment.getExternalStorageDirectory().getAbsolutePath()));    
  9.            sendBroadcast(intent);    
  10.                
  11.        }    
  12.            
  13.        private BroadcastReceiver scanSdReceiver = new BroadcastReceiver(){    
  14.           
  15.            private AlertDialog.Builder builder;    
  16.            private AlertDialog ad;    
  17.            @Override    
  18.            public void onReceive(Context context, Intent intent) {    
  19.                String action = intent.getAction();    
  20.              
  21.                if(Intent.ACTION_MEDIA_SCANNER_STARTED.equals(action)){    
  22.                    builder = new AlertDialog.Builder(context);    
  23.                    builder.setMessage("正在扫描sdcard...");    
  24.                    ad = builder.create();    
  25.                    ad.show();    
  26.                //    adapter.notifyDataSetChanged();    
  27.                }else if(Intent.ACTION_MEDIA_SCANNER_FINISHED.equals(action)){    
  28.                    ad.cancel();//重新获取文件数据信息    
  29.                    Toast.makeText(context, "扫描完毕", Toast.LENGTH_SHORT).show();    
  30.            }       
  31.        }    
  32.    };    
或者

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public void fileScan(File file){      
  2.         Uri data =  Uri.parse("file://"+ Environment.getExternalStorageDirectory())      
  3.   sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, data));      
  4.     }     

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void insertMeadia(ContentValues values){    
  2.          Uri uri = getContentResolver().insert( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);     
  3.          sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));    
  4.     }    

刷新所有系统文件,效率可能不高,高效方法是只刷新变化的文件

方式二:指定特定文件操作

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. File path = getExternalFilesDir(Environment.DIRECTORY_PICTURES);    
  2.        File file = new File(path, "DemoPicture.jpg");    
  3.     
  4.        try {    
  5.              
  6.            InputStream is = getResources().openRawResource(R.drawable.balloons);    
  7.            OutputStream os = new FileOutputStream(file);    
  8.            byte[] data = new byte[is.available()];    
  9.            is.read(data);    
  10.            os.write(data);    
  11.            is.close();    
  12.            os.close();    
  13.     
  14.            // Tell the media scanner about the new file so that it is    
  15.            // immediately available to the user.    
  16.            MediaScannerConnection.scanFile(this,    
  17.                    new String[] { file.toString() }, null,    
  18.                    new MediaScannerConnection.OnScanCompletedListener() {    
  19.                public void onScanCompleted(String path, Uri uri) {    
  20.                    Log.i("ExternalStorage""Scanned " + path + ":");    
  21.                    Log.i("ExternalStorage""-> uri=" + uri);    
  22.                }    
  23.            });    
  24.        } catch (IOException e) {    
  25.            // Unable to create file, likely because external storage is    
  26.            // not currently mounted.    
  27.            Log.w("ExternalStorage""Error writing " + file, e);    
  28.        }    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值