首先方法
sendMessage(message)应该在服务内部而不是
LocalBinder类中
public class SocketListener extends Service { public void sendMessage(String message){ socket.emit("match", message); }}
其次从片段访问活动方法,您应该在片段内部创建接口
interface MessageSender { void sendMessage(String message);}
然后在您的活动中实施
public class MainActivity extends AppCompatActivity implements MessageSender { @Override public void sendMessage(String message) { // call the service here socketService.sendMessage(message); }}
在片段中,实现
onAttach()并初始化接口实例
public class MainViewFragment extends Fragment { private MessageSender mMessageSenderCallback; @Override public void onAttach(Context context) { super.onAttach(context); try { mMessageSenderCallback = (MessageSender) context; } catch (ClassCastException e) { // Error, class doesn't implement the interface } } @Override public void onDetach() { super.onDetach(); // Remove activity reference mMessageSenderCallback = null; }}
要发送消息,请
mMessageSenderCallback.sendMessage(message)在片段内调用消息。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)