簡體   English   中英

從廣播接收器更新活動UI組件?

[英]Updating Activity UI component from Broadcast Receiver?

我有非常基本的問題。 這可能很簡單,但我不明白。 我有一個正在使用一些UI組件的Activity。 而且我還有一個廣播接收器(從清單中注冊) ,在這里我需要更新Activity類的一些UI組件。 喜歡 -

    Class MyActivity extends Activity
     {

        onCreate(){

         //using some UI component lets say textview
           textView.setText("Some Text");
        }

       updateLayout()
       {
         textView.setText("TextView Upadated...");
       }
 }


Class broadCastReceiver
{

    onReceive()
    {
       //here I want to update My Activity component like 
       UpdateLayout();

    }

} 

為此, 一種解決方案是使updateLayout()方法成為公共靜態方法 ,並通過活動引用在接收器類中使用該方法。 但是我認為,這不是正確的方法。是否有適當的方法?

可以在運行時注冊和注銷它,而不是在清單中注冊接收者:

另外,請確保您在意圖過濾器中以正確的操作注冊了接收器。

public class MyActivity extends Activity{

// used to listen for intents which are sent after a task was
// successfully processed
private BroadcastReceiver mUpdateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        new UpdateUiTask().execute();
    }
};

@Override
public void onResume() {        
    registerReceiver(mUpdateReceiver, new IntentFilter(
            YOUR_INTENT_ACTION));
    super.onResume();
}

@Override
public void onPause() {     
    unregisterReceiver(mUpdateReceiver);
    super.onPause();
}


// used to update the UI
private class UpdateUiTask extends AsyncTask<Void, Void, String> {

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected String doInBackground(Void... voids) {
        Context context = getApplicationContext();
        String result = "test";
        // Put the data obtained after background task. 
        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO: UI update          
    }
}  

}

希望能幫助到你。

如果確實必須繼續使用從AndroidManifest.xml注冊的BroadcastReceiver ,則可以考慮使用事件總線。 Square有一個很酷的開源庫Otto

它很好地實現了發布者/訂閱者模式。 您會在網上找到許多使用方法的示例,這非常簡單。 首先查看Otto的網站

如果您可以直接從Activity注冊/取消注冊接收者,那么我將遵循@Ritesh Gune的回答。

我當然會推薦GreenRobot的EventBus

EventBus是Android優化的發布/訂閱事件總線。 Android應用程序的一個典型用例是將“活動”,“片段”和“后台線程”粘合在一起。 這些元素的常規布線通常會引入復雜且容易出錯的依賴性以及生命周期問題。 隨着EventBus在所有參與者之間傳播的偵聽器(例如,后台服務->活動->多個片段或幫助程序類)已被棄用。 EventBus使事件發送方和接收方分離,從而簡化了應用程序組件之間的通信。 代碼更少,質量更高。 而且您不需要實現單個接口!

簽出: https : //github.com/greenrobot/EventBus

您可以將ObservableEvent與Extended Observable類一起使用。

public class ObservableEvent extends Observable {
public void setChanged(){
    super.setChanged();
}
}

制作單例課程通知中心

public class NSNotificationCenter {

private HashMap<String, ObservableEvent> observables = new HashMap<String, ObservableEvent>();

/**
 * Lazy load the event bus
 */

public void addObserver(String notification, Observer observer) {
    ObservableEvent observable = observables.get(notification);
    if (observable == null) {
        observable = new ObservableEvent();
        observables.put(notification, observable);
    }
    observable.addObserver(observer);
}

public void removeObserver(String notification, Observer observer) {
    Observable observable = observables.get(notification);
    if (observable != null) {
        observable.deleteObserver(observer);
    }
}


public void postNotification(String notification, Object object) { 
        ObservableEvent observable = observables.get(notification);
        if (observable != null) {
            observable.setChanged();
            if (object == null) { 
                observable.notifyObservers();
            } else {
                observable.notifyObservers(object);
            }
        } 
}

}

僅用於添加觀察者以觀察通知,而觸發方法則使用后通知

文檔

您可以使用Context.registerReceiver()動態注冊此類的實例,也可以通過AndroidManifest.xml中的標簽靜態發布實現。

Activity.onResume()實現中注冊接收者,並在Activity.onPause()注銷。

public class MyActivity extends Activity
{
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            MyActivity.this.broadcastReceived(intent);
        }
    };

    public void onResume() {
       super.onResume();
       IntentFilter intentFilter = new IntentFilter();
       // add action, category, data to intentFilter
       this.registerReceiver(this.mBroadcastReceiver, intentFilter);
    }

    public void onPause() {
       super.onPause();
       this.unregisterReceiver(this.mBroadcastReceiver);
    }

    public void broadcastReceived(Intent intent) {
       // Update the UI component here.
    }
}

您可以使用觀察者模式-活動在廣播接收器的onResume()中注冊自己,以接收更新,而在onPause()中注銷自身。

網上有很多材料可以學習觀察者模式-http: //en.wikipedia.org/wiki/Observer_pattern

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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