简体   繁体   中英

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.

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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