2017-09-14 180 views
0

我寫這將需要監視正在創建文件的文件夾,然後採取基於已創建的文件的文件名操作的應用程序。從類中發送廣播消息到活動中的Android

我已經使用的廣播接收器從電池和USB連接等來通知所以這將是很好能夠從正在實施fileObserver類發送廣播。

在主要活動我實現了fileObserver一個子類,但我無法弄清楚如何,在事件我可以通知文件被創建的主要活動。

這裏是子類

class FileListener extends FileObserver { 
private String mAbsolutePath; 

public FileListener(String path){ 
    super(path); 
    mAbsolutePath = path; 
    Log.d("FileObserver",path); 
} 

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

    switch(event){ 
     case FileObserver.CREATE: 
      Intent i = new Intent("CREATED"); 
      context.sendBroadcast(i); 
      break; 
     case FileObserver.DELETE: 
      Log.d("FileObserver", "DELETE"); 
      break; 
     case FileObserver.DELETE_SELF: 
      Log.d("FileObserver", "DELETE_SELF"); 
      break; 
     case FileObserver.MODIFY: 
      Log.d("FileObserver", "MODIFY"); 
      break; 
     case FileObserver.MOVED_FROM: 
      Log.d("FileObserver", "MOVED_FROM"); 
      break; 
     case FileObserver.MOVED_TO: 
      Log.d("FileObserver", "MOVED_TO"); 
      break; 
     case FileObserver.MOVE_SELF: 
      Log.d("FileObserver", "MOVE_SELF"); 
      break; 
    } 
} 

}

我不能在課堂上使用context.sendBroadcast因爲它沒有上下文。這非常混亂。

感謝

+3

你通過它在構造函數中的上下文。最好是應用上下文 –

回答

1

所有你需要做的是通過構造函數爲你的類像這樣:

class FileListener extends FileObserver { 
private String mAbsolutePath; 
private Context mContext; 

public FileListener(String path, Context context){ 
    super(path); 
    mAbsolutePath = path; 
    mContext = context; 
    Log.d("FileObserver",path); 
} 

//use context in your file. 

你可以調用像你這樣的類:new FileListener(path, getApplicationContext()從活動或片段。

相關問題