[英]Send Broadcast message from a class to an Activity in Android
我正在编写一个应用程序,该应用程序需要监视文件夹中正在创建的文件,然后根据所创建文件的文件名采取措施。
我已经在使用广播接收器来接收来自电池和USB连接的其他通知,因此能够从正在实现fileObserver的类中发送广播会很好。
在Main活动中,我为fileObserver实现了一个子类,但是我无法弄清楚如何在发生事件时通知MAin Activity已创建文件。
这是子类
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,因为它没有上下文。 这一切都很令人困惑。
谢谢
您需要做的就是将构造函数传递给您的类,如下所示:
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()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.