0

给定代码:

public class CommandSequence {

public CommandSequence() {
}

public void startCommunications(View v) {
    Bundle dataout1 = new Bundle();
    dataout1.putInt("ACTION", Communications.ACTION_LOAD_COMMAND_ONLY);
    dataout1.putInt("PORT", Commands.MESSAGE_TYPE_SMC);
    dataout1.putInt("COMMAND", Commands.SMC_RESETEVENTSTATUS);
    ((MainActivity) v.getContext()).sendMessageToBackgroundCommunicationsService(
        Communications.MESSAGE_LOAD_COMMAND,
        dataout1);
}
}

我必须使用调用活动上下文(即“MainActivity”)转换“sendMessageToBackgroundCommunicationsService()”。

是否可以传递一个允许我在运行时强制转换方法调用的参数,以便可以从任何活动类调用此方法?

4

1 回答 1

1

为什么不创建一个所有活动都继承的基本活动类,然后在需要调用时转换为该类:

((MyBaseActivity) v.getContext()).sendMessageToBackgroundCommunicationsService(
    Communications.MESSAGE_LOAD_COMMAND,
    dataout1);

[编辑] 事实上,为了让你的代码更好一点,你可以将活动传递给你的方法,这样就不需要你的类需要知道另一个类。

public void startCommunications(View v, Class myActivity) {
 //your code
}
于 2012-08-23T13:08:27.043 回答