簡體   English   中英

在Android中將廣播消息從類發送到活動

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM