2012-06-07 1 views
1

파일 Observer를 사용하여 파일을 삭제하려고합니다. 내 코드에서 파일이 SD 카드에 푸시되면 작성 이벤트가 발생합니다. 해당 이벤트에서 해당 파일을 삭제하려고합니다. 아래에 제공된 코드를 시도하고 있지만 파일 복사가 일어나기 때문에 파일을 삭제할 수 없습니다. 그래서 파일을 SD 카드에 성공적으로 복사 할 때 파일을 삭제하려고합니다.안드로이드에서 파일 옵저버를 사용하여 파일을 삭제하는 방법은 무엇입니까?

파일을 SD 카드에 성공적으로 복사 할 때 어떤 이벤트 알림이 발생합니까?

public class RecursiveFileObserver extends FileObserver 
{ 
    /** Only modification events */ 
    public static int CHANGES_ONLY = CREATE | DELETE | CLOSE_WRITE | MOVE_SELF 
    | MOVED_FROM | MOVED_TO; 

    List<SingleFileObserver> mObservers; 
    String mPath; 
    int mMask; 
    Context mContext; 

    public RecursiveFileObserver(String path, Context context) 
    { 
     this(path, ALL_EVENTS, context); 
    } 

    public RecursiveFileObserver(String path, int mask, Context context) 
    { 
     super(path, mask); 
     mPath = path; 
     mMask = mask; 
     mContext = context; 
    } 

    @Override 
    public void startWatching() 
    { 
     if (mObservers != null) 
      return ; 

     mObservers = new ArrayList(); 
     Stack stack = new Stack(); 
     stack.push(mPath); 

     while (!stack.isEmpty()) 
     { 
      String parent = String.valueOf(stack.pop()); 
      mObservers.add(new SingleFileObserver(parent, mMask)); 
      File path = new File(parent); 
      File[]files = path.listFiles(); 
      if (null == files) 
      continue; 
      for (File f: files) 
      { 
       if (f.isDirectory() && !f.getName().equals(".") && !f.getName().equals("..")) 
       { 
        stack.push(f.getPath()); 
       } 
      } 
     } 

     for (SingleFileObserver sfo: mObservers) 
     { 
      sfo.startWatching(); 
     } 
    } 

    @Override 
    public void stopWatching() 
    { 
     if (mObservers == null) 
      return ; 

     for (SingleFileObserver sfo: mObservers) 
     { 
      sfo.stopWatching(); 
     } 
     mObservers.clear(); 
     mObservers = null; 
    } 

    @Override 
    public void onEvent(int event, String path) 
    { 
     switch (event) 
     { 

      case FileObserver.CREATE: 
      Log.i("RecursiveFileObserver", "CREATE: " + path); 
      File file = new File(path); 
      Log.d("File length "," file length = "+file.length()); 

      if(file.exists()){ 
      boolean deleted = file.delete(); 
      Log.d("File Deteted "," file Delete = "+deleted); 
      } 
      break; 

     } 
    } 

    /** 
    * Monitor single directory and dispatch all events to its parent, with full path. 
    */ 
    class SingleFileObserver extends FileObserver 
    { 
     String mPath; 

     public SingleFileObserver(String path) 
     { 
      this(path, ALL_EVENTS); 
      mPath = path; 
     } 

     public SingleFileObserver(String path, int mask) 
     { 
      super(path, mask); 
      mPath = path; 
     } 

     @Override public void onEvent(int event, String path) 
     { 
      String newPath = mPath + "/" + path; 
      RecursiveFileObserver.this.onEvent(event, newPath); 
     } 
    } 
} 


    public class TestFileObserverActivity extends Activity { 

    RecursiveFileObserver mObserver; 


    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     mObserver = new RecursiveFileObserver(Environment.getExternalStorageDirectory().getAbsolutePath(), RecursiveFileObserver.CREATE, this); 
     mObserver.startWatching(); 

     Toast.makeText(getApplicationContext(), "Watching " + Environment.getExternalStorageDirectory().getAbsolutePath(), Toast.LENGTH_LONG).show(); 

    } 
} 

도와주세요. 미리 감사드립니다.

+0

이것은 나쁜 생각처럼 들립니다. –

답변

0

내 지식으로는 파일 복사가 완료된 것을 알 수있는 방법이 없습니다. 그러나 내가 생각할 수있는 일이있다. create 이벤트에서 3 초마다 파일 완료를 확인하는 timertask를 두십시오. 또는 존재하지 않을 때까지 3 초마다 삭제 한 다음 타이머 대기열에서 timertask를 가져옵니다. 이렇게하면 파일이 더 이상 존재하지 않을 때까지 복사기가 수행 한 작업을 계속 삭제합니다.

희망이 있습니다.

+0

관찰자 파일이 기반이되는 기본 linux inotify mechansim은 쓰기 위해 열린 파일이 닫힐 때 "CLOSE_WRITE"이벤트를보고하도록 설정할 수 있습니다. 파일 관찰자가이를 수행 할 수 있는지 또는 원시 코드에서 직접 inotify를 사용하는 데 장애가되는지 확실하지 않습니다. 파일 관찰자가 지원하지 않으면 여기에 제시된대로 기다리는 것이 더 간단 할 것입니다. 그러나 위에서 말했듯이 전체 프로젝트는 나쁜 생각처럼 보입니다. –

+0

당신 말이 맞아요. CLOSE_WRITE 완전히 내 마음을 탈출했다. 파일 옵저버 _does_ 지원 CLOSE_WRITE; CREATE와 마찬가지로 스위치를하면 작동합니다. 하나의 측면 ... 재귀 파일 관찰자를 설정하는 데 시간이 걸립니다. 사용자 인터페이스가 있다면 재귀 파일 관찰자 클래스에서 시작 감시 명령을 스레드하므로 UI ​​스레드를 바인딩하지 않습니다. –