android 广播监听 自动刷新,通过观察者模式监听媒体库的变化实现APP本地数据自动更新...

import java.io.UnsupportedEncodingException;

import java.util.ArrayList;

import java.util.Timer;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.content.IntentFilter;

import android.database.ContentObserver;

import android.database.Cursor;

import android.net.Uri;

import android.os.AsyncTask;

import android.os.Handler;

import android.provider.MediaStore;

/**

* 自动更新书架

*

* */

public class AutoRefreshBookShelf {

public AutoRefreshBookShelf(   Context context, AutoRefreshListener autoRefreshListener, String[]   supportSuffix ) throws NullPointerException{

if(   null == context || null == autoRefreshListener || null == supportSuffix ){

throw   new NullPointerException( "传非空的参数进来!" );

}

mContext   = context;

mAutoRefreshListener   = autoRefreshListener;

mSupportSuffix   = supportSuffix;

initAutoRefreshBookShelf(   );

}

// 不在本界面停止后台检索

public void onPause( ){

stopCheckFileTimer(   );

}

// 返回界面恢复后台检索

public void onResume( ){

startCheckFileTimer(   );

}

/**

* 注销广播

*

* */

public void unregisterAutoRefreshBookShelf(   ) throws NullPointerException{

if(   null == mBroadcastReceiver || null == mMediaStoreChangeObserver || null ==   mContext ){

throw   new NullPointerException( "没有初始化" );

}

mContext.unregisterReceiver(   mBroadcastReceiver );

mContext.getContentResolver(   ).unregisterContentObserver( mMediaStoreChangeObserver );

stopCheckFileTimer(   );

}

/**

* 得到变化的文件列表

*

* */

public void getChangedFileList(   ){

System.out.println(   "toast ================= getChangedFileList " );

startCheckFileTimer(   );

}

private void initAutoRefreshBookShelf(   ){

startMediaFileListener(   );

observerMediaStoreChange(   );

}

private void observerMediaStoreChange(   ){

if(   null == mMediaStoreChangeObserver ){

mMediaStoreChangeObserver   = new MediaStoreChangeObserver( );

}

mContext.getContentResolver(   ).registerContentObserver(   MediaStore.Files.getContentUri("external"), false, mMediaStoreChangeObserver   );

}

/**

* 监听USB的状态,更新书架书本信息

*

* */

private void startMediaFileListener(   ){

if(   null != mBroadcastReceiver ){

return;

}

IntentFilter   intentFilter = new IntentFilter( );

intentFilter.addAction(   Intent.ACTION_MEDIA_SCANNER_FINISHED );

intentFilter.addAction(   Intent.ACTION_MEDIA_MOUNTED );

intentFilter.addAction(   Intent.ACTION_MEDIA_EJECT );

intentFilter.addDataScheme(   "file" );

mBroadcastReceiver   = new BroadcastReceiver(){

@Override

public   void onReceive(Context context,Intent intent){

String   action = intent.getAction( );

if(   Intent.ACTION_MEDIA_SCANNER_FINISHED.equals( action ) ){

System.out.println(   "toast ================= ACTION_MEDIA_SCANNER_FINISHED " );

mTimerWorking   = false;

startCheckFileTimer(   );

}else   if( action.equals( Intent.ACTION_MEDIA_MOUNTED ) ){

System.out.println(   "toast ================= ACTION_MEDIA_MOUNTED or ACTION_MEDIA_EJECT   " );

mTimerWorking   = true;

mAutoRefreshListener.onBookScan(   );

}else   if( action.equals( Intent.ACTION_MEDIA_EJECT ) ){

mAutoRefreshListener.onBookScan(   );

}

}

};

mContext.registerReceiver(   mBroadcastReceiver, intentFilter );//注册监听函数

}

/**

* 媒体数据库变更观察类

*

* */

class MediaStoreChangeObserver   extends ContentObserver{

public MediaStoreChangeObserver(   ) {

super(   new Handler( ) );

}

@Override

public void   onChange(boolean selfChange) {

super.onChange(selfChange);

startCheckFileTimer(   );

}

}

private void startCheckFileTimer(   ){

if(   mTimerWorking ){

return;

}

mCheckFileTimer   = new Timer( );

mCheckFileTimer.schedule(   new CheckFileChangeTimerTask( ), 5000 );

mTimerWorking   = true;

}

private void stopCheckFileTimer(   ){

if(   null != mCheckFileTimer ){

mCheckFileTimer.cancel(   );

mCheckFileTimer   = null;

mTimerWorking   = false;

}

}

/**

* 得到新增的文件列表

*

* */

public ArrayList getChangedFileList(   Context context, String[] searchFileSuffix, ArrayList   existFileList ){

ArrayList   changedFileList = null;

if(   null == context || null == searchFileSuffix ){

return   changedFileList;

}

ArrayList   supportFileList = getSupportFileList( context, searchFileSuffix );

changedFileList   = getDifferentFileList( supportFileList, existFileList );

if(   null == changedFileList || changedFileList.size( ) == 0 ){

changedFileList   = null;

}

return changedFileList;

}

/**

* 获取新增的文件列表

*

* */

private ArrayList   getDifferentFileList( ArrayList newFileList,   ArrayList existFileList ){

ArrayList   differentFileList = null;

if(   null == newFileList || newFileList.size( ) == 0 ){

return   differentFileList;

}

differentFileList   = new ArrayList( );

boolean   isExist = false;

if(   null == existFileList ){

//   如果已存在文件为空,那肯定是全部加进来啦。

for(   String newFilePath : newFileList ){

differentFileList.add(   newFilePath );

}

}else{

for(   String newFilePath : newFileList ){

isExist   = false;

for(   String existFilePath : existFileList ){

if(   existFilePath.equals( newFilePath ) ){

isExist   = true;

break;

}

}

if(   !isExist ){

differentFileList.add(   newFilePath );

}

}

}

return differentFileList;

}

/**

* 从媒体库中获取指定后缀的文件列表

*

* */

public ArrayList   getSupportFileList( Context context, String[] searchFileSuffix ) {

ArrayList   searchFileList = null;

if(   null == context || null == searchFileSuffix || searchFileSuffix.length == 0 ){

return   null;

}

String   searchPath = "";

int length   = searchFileSuffix.length;

for(   int index = 0; index < length; index++ ){

searchPath   += ( MediaStore.Files.FileColumns.DATA + " LIKE '%" +   searchFileSuffix[ index ] + "' " );

if(   ( index + 1 ) < length ){

searchPath   += "or ";

}

}

searchFileList   = new ArrayList();

Uri uri   = MediaStore.Files.getContentUri("external");

Cursor   cursor = context.getContentResolver().query(

uri,   new String[] { MediaStore.Files.FileColumns.DATA,   MediaStore.Files.FileColumns.SIZE, MediaStore.Files.FileColumns._ID },

searchPath,   null, null);

String   filepath = null;

if (cursor   == null) {

System.out.println("Cursor   获取失败!");

} else {

if   (cursor.moveToFirst()) {

do   {

filepath   = cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA));

try   {

searchFileList.add(new   String(filepath.getBytes("UTF-8")));

}   catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

}   while (cursor.moveToNext());

}

if   (!cursor.isClosed()) {

cursor.close();

}

}

return searchFileList;

}

/**

* 得到媒体库更新的文件

*

* */

class GetMediaStoreDataTask   extends AsyncTask< Void , Void , Void>{

@Override

protected   Void doInBackground(Void... arg0) {

ArrayList   changedFileList = getChangedFileList( mContext, mSupportSuffix,   mAutoRefreshListener.onGetBookPathList( ) );

if(   null != changedFileList && changedFileList.size( ) > 0 ){

mAutoRefreshListener.onBookRefresh(   changedFileList );

}

mTimerWorking   = false;

return   null;

}

}

class CheckFileChangeTimerTask   extends java.util.TimerTask{

@Override

public void   run() {

new   GetMediaStoreDataTask( ).execute( );

}

}

/**

* 书架自动刷新接口

*

* */

public interface AutoRefreshListener{

public ArrayList   onGetBookPathList( ); // 得到书架书本列表

public void   onBookRefresh( ArrayList bookInfoList );// 刷新书架

public void   onBookScan( );//全盘扫描书架

}

private boolean mTimerWorking =   false;

private Context mContext =   null;

private String[] mSupportSuffix   = null;

private BroadcastReceiver   mBroadcastReceiver = null;

private MediaStoreChangeObserver   mMediaStoreChangeObserver = null;

private AutoRefreshListener   mAutoRefreshListener = null;

private Timer mCheckFileTimer =   null;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值