BroadCaseReceiver使用,動態註冊,在項目中調用

今天寫一個BroadCaseReceiver在項目中的使用,BroadCaseReceiver刪除文件夾中所有文件的操作。

 

首先在你的Activity中註冊你的BroadcaseReceiver,在android7.0之後,BroadCaseReceiver靜態註冊是收不到廣播的,別踩坑!

 public BRClearUeLog clearUeLog;

if (clearUeLog == null) {
            clearUeLog = new BRClearUeLog();
            IntentFilter intentFilter = new IntentFilter();

           //Action是你給你的BroadcaseReceiver起的標識碼,俗稱tag
            intentFilter.addAction("com.android.clearUeLog");
            registerReceiver(clearUeLog, intentFilter);

           //這裏可以簡寫爲registerReceiver(clearUeLog , new IntentFilter("com.android.clearUeLog"));
        }

當然有註冊就有反註冊,在你的Activity結束的時候進行反註冊,優化內存空間,避免內存溢出

if (clearUeLog != null) {
            unregisterReceiver(clearUeLog);
            clearUeLog = null;
        }

 

然後是Activity的調用:

       Intent intent = new Intent();  

      //與上面的Action所對應
        intent.setAction("com.android.clearUeLog");  

      //如果傳輸數據可以用此方式
       //intent.putExtra("message","我是數據");  
        sendBroadcast(intent);

最後大招來了,BroadcaseReceiver正文:

/**
 * 刪除adbtestcase文件夾下的所有文件,並反饋是否清理成功與否
 * @author Android
 *
 */
public class BRClearUeLog extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        //如果有傳輸的Intent數據intent.getStringExtra("message")取出
        String path="刪除文件的路徑";
        
        deleteDir(path);
        
        isNull(path);
        
    }
    
    //檢查adbtestcase文件夾下是否爲空
    private void isNull(String path) {
        // TODO Auto-generated method stub

        File file = new File(path);
        File[] listFiles = file.listFiles();
        if (listFiles.length > 0) {
            //文件夾下有文件
            ConfigTest.currentCmdState="清理失敗";
        } else {
            // 文件夾下沒有文件
            ConfigTest.currentCmdState="清理成功";
        }
    }

    //刪除文件夾和文件夾裏面的文件
    private  void deleteDir(String pPath) {
        File dir = new File(pPath);
        deleteDirWihtFile(dir);
    }

    private void deleteDirWihtFile(File dir) {
        if (dir == null || !dir.exists() || !dir.isDirectory()) {
            return;
        } else {
            File[] files = dir.listFiles();
            Log.e("motejia", "deleteDirWihtFile: ==============="+files.length );
            for (File file : dir.listFiles()) {
                if (file.isFile()) {
                    file.delete(); // 刪除所有文件
                } else if (file.isDirectory()) {
                    deleteDirWihtFile(file); // 遞規的方式刪除文件夾
                    file.delete();
                }
            }

            // dir.delete();// 刪除目錄本身
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章