简体   繁体   English

如何将数据从广泛的广播接收者传递到主要活动

[英]how to pass data from broad cast receiver to main activity

I registered a broad cast receiver in a separate file from the main activity, and based on the received notifications in the broad cast receiver, i want to perform some action in the main activity. 我在与主要活动分开的单独文件中注册了广泛演员接收器,并根据广泛演员接收器中收到的通知,我想在主要活动中执行一些操作。

my question is, what is the recommended way to pass the notifications from the broad cast receiver to the main activity? 我的问题是,将通知从广泛的广播接收者传递到主要活动的推荐方法是什么? should make a public method inside each Action iam registered for in the broad cast receiver file? 在广泛的转换接收者文件中注册的每个Action IAM内都应该公开方法? or should use an interface that will be implemented in the main activity. 或应使用将在主要活动中实现的接口。

note: the broad cast reciever is registered for 7 actions 注意:广泛的接收者已注册7次动作

Create an Interface and let your Main activity Implement it,this helps in Polymorphism Pass in your MainActivity object as the Interface to the BroadcastListener File and call the appropriate methods in the interface based on the actions.( Since you are mentioning to either have public methods i believe you will have the reference to the MainActivity object). 创建一个接口并让您的Main活动实现它,这有助于多态性将MainActivity对象作为BroadcastListener文件的接口传递,并根据这些操作在接口中调用适当的方法。(由于您提到的都是公共方法我相信您将引用MainActivity对象)。 Implement it more like the Observer Pattern. 像观察者模式一样实现它。

//BroadcastObserver.java
public interface BroadcastObserver {
    //methods methods 
   public void foo();
}

//MainActivity.java
public class MainActivity extends Activity implements BroadcastObserver{
 @Override
 public void foo(){

 }

}

public class MyClass {
  BroadcastObserver static observer;  // this should be set to by passing your MainActivity object, may be at the time when you initiate your MyClass object
  public static class MyBroadcastReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {
     Toast.makeText(context, "!!!!.",
     Toast.LENGTH_LONG).show();
     if(someaction){
         observer.foo();
     }
  }


}

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

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