简体   繁体   English

从广播接收器更新活动UI组件?

[英]Updating Activity UI component from Broadcast Receiver?

I have very basic ques. 我有非常基本的问题。 and it might be very simple but i am not getting it. 这可能很简单,但我不明白。 I have an Activity where I am using some UI component. 我有一个正在使用一些UI组件的Activity。 and I also have a broadcast receiver (registering from manifest) where I need to update some UI component of Activity class. 而且我还有一个广播接收器(从清单中注册) ,在这里我需要更新Activity类的一些UI组件。 Like - 喜欢 -

    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();

    }

} 

For that- One solution is that make the updateLayout() method public static , and use that method in receiver class by activity reference . 为此, 一种解决方案是使updateLayout()方法成为公共静态方法 ,并通过活动引用在接收器类中使用该方法。 But I think, this is not the right way to do this.. Is there any proper way to do that? 但是我认为,这不是正确的方法。是否有适当的方法?

Instead of registering a receiver in manifest, you can register and unregister it at runtime as follows: 可以在运行时注册和注销它,而不是在清单中注册接收者:

Also make sure you register your receiver with correct Action in Intent Filter. 另外,请确保您在意图过滤器中以正确的操作注册了接收器。

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

}

Hope it helps. 希望能帮助到你。

If you really have to keep using BroadcastReceiver registered from AndroidManifest.xml then you could consider using event bus. 如果确实必须继续使用从AndroidManifest.xml注册的BroadcastReceiver ,则可以考虑使用事件总线。 There is one cool open source library Otto from Square . Square有一个很酷的开源库Otto

It's implementing publisher/subscriber pattern very nicely. 它很好地实现了发布者/订阅者模式。 You will find many examples on the web how to use it, it's very simple. 您会在网上找到许多使用方法的示例,这非常简单。 First of all check out the Otto's website 首先查看Otto的网站

If you can register/unregister receiver directly from Activity then I would follow @Ritesh Gune answer. 如果您可以直接从Activity注册/取消注册接收者,那么我将遵循@Ritesh Gune的回答。

I'd certainly recommend EventBus from GreenRobot 我当然会推荐GreenRobot的EventBus

EventBus is an Android optimized publish/subscribe event bus. EventBus是Android优化的发布/订阅事件总线。 A typical use case for Android apps is gluing Activities, Fragments, and background threads together. Android应用程序的一个典型用例是将“活动”,“片段”和“后台线程”粘合在一起。 Conventional wiring of those elements often introduces complex and error-prone dependencies and life cycle issues. 这些元素的常规布线通常会引入复杂且容易出错的依赖性以及生命周期问题。 With EventBus propagating listeners through all participants (eg background service -> activity -> multiple fragments or helper classes) becomes deprecated. 随着EventBus在所有参与者之间传播的侦听器(例如,后台服务->活动->多个片段或帮助程序类)已被弃用。 EventBus decouples event senders and receivers and thus simplifies communication between app components. EventBus使事件发送方和接收方分离,从而简化了应用程序组件之间的通信。 Less code, better quality. 代码更少,质量更高。 And you don't need to implement a single interface! 而且您不需要实现单个接口!

check out : https://github.com/greenrobot/EventBus 签出: https : //github.com/greenrobot/EventBus

you can use ObservableEvent with extends Observable class. 您可以将ObservableEvent与Extended Observable类一起使用。

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

Make singleton class notification center 制作单例课程通知中心

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

} }

just use to add observer for observing notify and for firing method use post notification 仅用于添加观察者以观察通知,而触发方法则使用后通知

From the docs : 文档

You can either dynamically register an instance of this class with Context.registerReceiver() or statically publish an implementation through the tag in your AndroidManifest.xml. 您可以使用Context.registerReceiver()动态注册此类的实例,也可以通过AndroidManifest.xml中的标签静态发布实现。

Register a receiver in Activity.onResume() implementation and unregister in Activity.onPause() . 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.
    }
}

You can use observer pattern-the activity registers itself in onResume() with the broadcast receiver to receive updates and in onPause() unregisters itself. 您可以使用观察者模式-活动在广播接收器的onResume()中注册自己,以接收更新,而在onPause()中注销自身。

There are lot of material on net to learn observer pattern- http://en.wikipedia.org/wiki/Observer_pattern 网上有很多材料可以学习观察者模式-http: //en.wikipedia.org/wiki/Observer_pattern

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

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