简体   繁体   English

在Android中将广播消息从类发送到活动

[英]Send Broadcast message from a class to an Activity in Android

I am writing an application that will need to monitor a folder for files being created and then take actions based on the file name of the file that was created. 我正在编写一个应用程序,该应用程序需要监视文件夹中正在创建的文件,然后根据所创建文件的文件名采取措施。

I am already using a Broadcast Receiver for other notifications coming from the battery and the usb connection so it would be nice to be able to send a broadcast from the class that is implementing a fileObserver. 我已经在使用广播接收器来接收来自电池和USB连接的其他通知,因此能够从正在实现fileObserver的类中发送广播会很好。

In the Main activity I implemented a sub class for the fileObserver but I cannot figure out how, upon an event I can notify the MAin Activity that a file was created. 在Main活动中,我为fileObserver实现了一个子类,但是我无法弄清楚如何在发生事件时通知MAin Activity已创建文件。

Here is the Sub Class 这是子类

    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;
    }
}

} }

I can't use context.sendBroadcast in the class because it has no context. 我不能在类中使用context.sendBroadcast,因为它没有上下文。 This is all very confusing. 这一切都很令人困惑。

Thanks 谢谢

All you need to do is pass your constructor into you class like so: 您需要做的就是将构造函数传递给您的类,如下所示:

  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.

You can then call you class like: new FileListener(path, getApplicationContext() from your activity or fragment. 然后可以从活动或片段中调用类,例如: new FileListener(path, getApplicationContext()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM