0

假设我有以下主要活动:

public class MwConsoleActivity extends Activity {

    private classChild child = null;    

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        child = new classChild();
    }
}

然后考虑类“classChild”的实现:

public class MwBondingAgent extends SapereAgent {

    MwBondingAgent(){}

    public void AddEventListener(childAddedEvent event) {

       //Send the data of event back to the main activity

    }
}

我尝试使用 IntentServices 但无法将值接收回主要活动。我将采取什么方法?

干杯阿里

4

3 回答 3

2

您可以使用和 intentFilter 来收听广播。将此添加到活动中:

 IntentFilter intentFilter = new IntentFilter(
                "com.unique.name");
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                //extract our message from intent
                String msg_for_me = intent.getStringExtra("some_msg");
             }
        };
        //registering our receiver
        this.registerReceiver(mReceiver, intentFilter);

在您的班级中,将此添加到您要通知活动的部分:

Intent i = new Intent("com.unique.name").putExtra("some_msg", "I have been updated!");
this.sendBroadcast(i);
于 2012-10-31T14:41:47.100 回答
1

您应该使用观察者/听众模式。

http://www.vogella.com/articles/DesignPatternObserver/article.html

在使用 MVC 架构模式时,它是最常用的设计模式之一。

于 2012-10-31T14:38:08.137 回答
1

您的问题很不清楚,但我认为您想要的是实现对您的活动的回调。您可以使用界面来执行此操作。

public class MwConsoleActivity extends Activity implements MwBondingAgent{

    private classChild child = null;    

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        child = new classChild();
    }

    @Override
    public void gotEventData(EventData myEventData) {

        //to whatever you want with myEventData
    }
}

在你的另一个班级。

public class MwBondingAgent extends SapereAgent {

    private MwBondingAgentCallback activityCallback;

    MwBondingAgent(Activity callback){

         activityCallback = callback;
    }

    public void AddEventListener(childAddedEvent event) {

        //Send the data of event back to the main activity
        EventData myEventData = //got some event data;
        //Send it back to activity
        activityCallback.gotEventData(myEventData);
    }

    public interface MwBondingAgentCallback {

        public void gotEventData(EventData myEventData);
    }
}
于 2012-10-31T14:39:46.970 回答