从DialogFragment关闭套接字

时间:2014-04-05 21:28:11

标签: android sockets

我有一个Activity正在运行一个线程,该线程有一个DatagramSocket侦听端口的数据包。基本上,当弹出一个对话框时,如果用户按下“接受”按钮,我想关闭Socket,然后开始另一个Activity。如何从Socket关闭DialogFragment

public class OnlineUsers extends Activity {
    //some code
    MsgFwd mservice;
    private final Handler mhandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REQUEST_CHAT:
                    String sourceIP = (String) msg.obj;
                    //SHOW DIALOG
                    MyAlert myAlert = new MyAlert();
                    Bundle args = new Bundle();
                    args.putString(BUNDLE_KEY_MYIP, myIP);
                    myAlert.setArguments(args);
                    myAlert.show(getFragmentManager(), "My Alert");
                    break;
            }
        }

        protected void onCreate(Bundle savedInstanceState) {
            mservice = new MsgFwd(this, mhandler);
            mservice.start();
        }
    }

    public class MsgFwd {

        Context fContext;
        private final Handler fHandler;
        fthread fconthread;

        public MsgFwd(Context context, Handler handler) {
            fContext = context;
            fHandler = handler;
        }

        public synchronized void start() {
            fconthread = new fthread();
            fconthread.start();
        }

        public synchronized void stop() {
           if (fconthread!=null){fconthread.cancel();fconthread = null;}
        }

        private class fthread extends Thread {
            //...
            DatagramSocket sock;

            public fthread() {
                sock = new DatagramSocket(someport);
            }

            void run() {
                while (true) {
                    sock.receive(packet);
                }
            }

            public void cancel() {
                try {
                    sock.close();
                } catch (Exception e) {
                }
            }
        }
    }

    public class MyAlert extends DialogFragment {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {

            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("Chat Notification");
            builder.setMessage(chatid + " wants to chat with you");
            builder.setNegativeButton("Reject", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Toast.makeText(getActivity(), "Negative button was clicked", Toast.LENGTH_SHORT).show();
                }
            });
            builder.setPositiveButton("Accept", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Toast.makeText(getActivity(), "Positive button was clicked", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(getActivity().getBaseContext(), newMessageFwd.class);
                    startActivity(intent);
                }
            });
            Dialog dialog = builder.create();

            return dialog;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

基本上你需要做的是为你的DialogFragment添加一个监听器,当用户点击accept时会调用它,然后告诉线程Socket应该被关闭。为此,我们将修改您的MyAlert Fragment。在旁注:通常你会将监听器定义嵌套在Fragment内,但由于你没有发布完整的代码,我无法确定这是否适用于你的情况,例如MyAlert必须是静态的以允许进一步嵌套,如果您在Activity中使用DialogFragment的成员变量,则可能会破坏您的代码。因此,您必须决定将侦听器接口放在何处,如果可能,请将其嵌套在Fragment中。无论如何这里是监听器接口:

public interface MyAlertAcceptListener {
    public void onAccept();
}

现在我们将监听器实现添加到Fragment,正如我已经指出的那样,如果可能的话,你还应该将监听器接口嵌套在那里:

public class MyAlert extends DialogFragment {

    private MyAlertAcceptListener alertListener;

    public MyAlertAcceptListener getAlertListener() {
        return alertListener;
    }

    public void setAlertListener(MyAlertAcceptListener listener) {
        this.alertListener = listener;
    }

    protected void notifyAcceptListener() {
        if(this.alertListener != null) {
            this.alertListener.onAccept();
        }
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Chat Notification");
        builder.setMessage(chatid + " wants to chat with you");
        builder.setNegativeButton("Reject", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getActivity(), "Negative button was clicked", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setPositiveButton("Accept", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getActivity(), "Positive button was clicked", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getActivity().getBaseContext(), MainActivity.class);
                startActivity(intent);

                // Notify the listener when the user presses accept
                notifyAcceptListener(); 
            }
        });
        Dialog dialog = builder.create();

        return dialog;
    }
}

现在当您在处理程序中打开DialogFragment时,您只需要像这样设置监听器:

public void handleMessage(Message msg) {
    switch (msg.what) {
        case REQUEST_CHAT:
            String sourceIP = (String) msg.obj;
            //SHOW DIALOG
            MyAlert myAlert = new MyAlert();
            Bundle args = new Bundle();
            args.putString(BUNDLE_KEY_MYIP, myIP);
            myAlert.setArguments(args);

            myAlert.setAlertListener(new MyAlertAcceptListener() {
                @Override
                public void onAccept() {
                    // In your Listener call stop() on mservice to close the socket
                    mservice.stop();
                }
            });

            myAlert.show(getFragmentManager(), "My Alert");
            break;
    }
}

如果您愿意,您也可以像使用处理程序一样定义您的监听器:

private final MyAlertAcceptListener acceptListener = new MyAlertAcceptListener() {
    @Override
    public void onAccept() {
        mservice.stop();
    }
};

然后你必须像这样设置它:

myAlert.setAlertListener(acceptListener);

如果您有任何进一步的问题,请随时询问!

编辑:我修改了我的示例代码以适合您的项目