XMPP and ANDROID

2019-08-15 04:38发布

问题:

I am trying to make XMPP client for android using

http://davanum.wordpress.com/2007/12/31/android-just-use-smack-api-for-xmpp/

I have been facing multiple issues in it

First of all my host name and service name are both same i.e. web.vlivetech.com

Then i do not know which jar file do i ned to include in my lib folder as i previously have included

1- asmack-android-7 but it was giving me error on some classes that NoClassDefFound

then now i have removed it and included

smack-3.4.1-0cec571.jar

but it is giving me error

NetworkOnMainThread

Here is my code for XMPPClient

public class XMPPClient extends Activity {

    private ArrayList<String> messages = new ArrayList();
    private Handler mHandler = new Handler();
    private SettingsDialog mDialog;
    private EditText mRecipient;
    private EditText mSendText;
    private ListView mList;
    private XMPPConnection connection;

    /**
     * Called with the activity is first created.
     */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.activity_xmppclient);

        mRecipient = (EditText) this.findViewById(R.id.recipient);
        mSendText = (EditText) this.findViewById(R.id.sendText);
        mList = (ListView) this.findViewById(R.id.listMessages);
        setListAdapter();

        // Dialog for getting the xmpp settings
        mDialog = new SettingsDialog(this);

        // Set a listener to show the settings dialog
        Button setup = (Button) this.findViewById(R.id.setup);
        setup.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                mHandler.post(new Runnable() {
                    public void run() {
                        mDialog.show();
                    }
                });
            }
        });

        // Set a listener to send a chat text message
        Button send = (Button) this.findViewById(R.id.send);
        send.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                String to = mRecipient.getText().toString();
                String text = mSendText.getText().toString();

                Log.i("XMPPClient", "Sending text [" + text + "] to [" + to + "]");
                Message msg = new Message(to, Message.Type.chat);
                msg.setBody(text);
                connection.sendPacket(msg);
                messages.add(connection.getUser() + ":");
                messages.add(text);
                setListAdapter();
            }
        });
    }

    /**
     * Called by Settings dialog when a connection is establised with the XMPP server
     *
     * @param connection
     */
    public void setConnection
            (XMPPConnection
                    connection) {
        this.connection = connection;
        if (connection != null) {
            // Add a packet listener to get messages sent to us
            PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
            connection.addPacketListener(new PacketListener() {
                public void processPacket(Packet packet) {
                    Message message = (Message) packet;
                    if (message.getBody() != null) {
                        String fromName = StringUtils.parseBareAddress(message.getFrom());
                        Log.i("XMPPClient", "Got text [" + message.getBody() + "] from [" + fromName + "]");
                        messages.add(fromName + ":");
                        messages.add(message.getBody());
                        // Add the incoming message to the list view
                        mHandler.post(new Runnable() {
                            public void run() {
                                setListAdapter();
                            }
                        });
                    }
                }
            }, filter);
        }
    }

    private void setListAdapter
            () {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.two_line_list_item,
                messages);
        mList.setAdapter(adapter);
    }

}

and here is the code for SettingsDiologue

public class SettingsDialog extends Dialog implements android.view.View.OnClickListener {
    private XMPPClient xmppClient;

    public SettingsDialog(XMPPClient xmppClient) {
        super(xmppClient);
        this.xmppClient = xmppClient;
    }

    protected void onStart() {
        super.onStart();
        setContentView(R.layout.settings);
        getWindow().setFlags(4, 4);
        setTitle("XMPP Settings");
        Button ok = (Button) findViewById(R.id.ok);
        ok.setOnClickListener(this);
    }

    public void onClick(View v) {
        String host = "web.vlivetech.com"; //getText(R.id.host);
        String port = "5222";  //getText(R.id.port);
        String service = "web.vlivetech.com"; //getText(R.id.service);
        String username = "khubaib"; //getText(R.id.userid);
        String password = "khubaib"; //getText(R.id.password);

        // Create a connection
        ConnectionConfiguration connConfig =
                new ConnectionConfiguration(host, Integer.parseInt(port));
        XMPPConnection connection = new XMPPConnection(connConfig);

        try {
            connection.connect();
            Log.i("XMPPClient", "[SettingsDialog] Connected to " + connection.getHost());
        } catch (XMPPException ex) {
            Log.e("XMPPClient", "[SettingsDialog] Failed to connect to " + connection.getHost());
            xmppClient.setConnection(null);
        }
        try {
            connection.login(username, password);
            Log.i("XMPPClient", "Logged in as " + connection.getUser());

            // Set the status to available
            Presence presence = new Presence(Presence.Type.available);
            connection.sendPacket(presence);
            xmppClient.setConnection(connection);
        } catch (XMPPException ex) {
            Log.e("XMPPClient", "[SettingsDialog] Failed to log in as " + username);
            xmppClient.setConnection(null);
        }
        dismiss();
    }

    private String getText(int id) {
        EditText widget = (EditText) this.findViewById(id);
        return widget.getText().toString();
    }

Am i missing something? or is there really problem with the jar file? any suggestions?

Here is the latest error Log

03-06 16:11:22.055: E/AndroidRuntime(6196): FATAL EXCEPTION: main
03-06 16:11:22.055: E/AndroidRuntime(6196): android.os.NetworkOnMainThreadException
03-06 16:11:22.055: E/AndroidRuntime(6196):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1108)
03-06 16:11:22.055: E/AndroidRuntime(6196):     at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
03-06 16:11:22.055: E/AndroidRuntime(6196):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
03-06 16:11:22.055: E/AndroidRuntime(6196):     at java.net.InetAddress.getByName(InetAddress.java:295)
03-06 16:11:22.055: E/AndroidRuntime(6196):     at java.net.InetSocketAddress.<init>(InetSocketAddress.java:105)
03-06 16:11:22.055: E/AndroidRuntime(6196):     at java.net.InetSocketAddress.<init>(InetSocketAddress.java:90)
03-06 16:11:22.055: E/AndroidRuntime(6196):     at org.jivesoftware.smack.proxy.DirectSocketFactory.createSocket(DirectSocketFactory.java:45)
03-06 16:11:22.055: E/AndroidRuntime(6196):     at org.jivesoftware.smack.XMPPConnection.connectUsingConfiguration(XMPPConnection.java:557)
03-06 16:11:22.055: E/AndroidRuntime(6196):     at org.jivesoftware.smack.XMPPConnection.connect(XMPPConnection.java:1010)
03-06 16:11:22.055: E/AndroidRuntime(6196):     at com.example.test.SettingsDialog.onClick(SettingsDialog.java:46)
03-06 16:11:22.055: E/AndroidRuntime(6196):     at android.view.View.performClick(View.java:3574)
03-06 16:11:22.055: E/AndroidRuntime(6196):     at android.view.View$PerformClick.run(View.java:14293)
03-06 16:11:22.055: E/AndroidRuntime(6196):     at android.os.Handler.handleCallback(Handler.java:605)
03-06 16:11:22.055: E/AndroidRuntime(6196):     at android.os.Handler.dispatchMessage(Handler.java:92)
03-06 16:11:22.055: E/AndroidRuntime(6196):     at android.os.Looper.loop(Looper.java:137)
03-06 16:11:22.055: E/AndroidRuntime(6196):     at android.app.ActivityThread.main(ActivityThread.java:4448)
03-06 16:11:22.055: E/AndroidRuntime(6196):     at java.lang.reflect.Method.invokeNative(Native Method)
03-06 16:11:22.055: E/AndroidRuntime(6196):     at java.lang.reflect.Method.invoke(Method.java:511)
03-06 16:11:22.055: E/AndroidRuntime(6196):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
03-06 16:11:22.055: E/AndroidRuntime(6196):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
03-06 16:11:22.055: E/AndroidRuntime(6196):     at dalvik.system.NativeStart.main(Native Method)

UPDATED LOG FILE AFTER IMPLEMENTING THE WAY SUGGESTED BY NAVEEN

03-06 17:08:26.235: E/AndroidRuntime(12037): FATAL EXCEPTION: AsyncTask #1
03-06 17:08:26.235: E/AndroidRuntime(12037): java.lang.RuntimeException: An error occured while executing doInBackground()
03-06 17:08:26.235: E/AndroidRuntime(12037):    at android.os.AsyncTask$3.done(AsyncTask.java:278)
03-06 17:08:26.235: E/AndroidRuntime(12037):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
03-06 17:08:26.235: E/AndroidRuntime(12037):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
03-06 17:08:26.235: E/AndroidRuntime(12037):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
03-06 17:08:26.235: E/AndroidRuntime(12037):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-06 17:08:26.235: E/AndroidRuntime(12037):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
03-06 17:08:26.235: E/AndroidRuntime(12037):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
03-06 17:08:26.235: E/AndroidRuntime(12037):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
03-06 17:08:26.235: E/AndroidRuntime(12037):    at java.lang.Thread.run(Thread.java:856)
03-06 17:08:26.235: E/AndroidRuntime(12037): Caused by: java.lang.NullPointerException
03-06 17:08:26.235: E/AndroidRuntime(12037):    at com.example.test.NetworkOperation.doInBackground(NetworkOperation.java:33)
03-06 17:08:26.235: E/AndroidRuntime(12037):    at com.example.test.NetworkOperation.doInBackground(NetworkOperation.java:1)

回答1:

You need to connect to Internet other that main thread i.e AsyncTask or any Thread.

If you run the network operation on main thread then you can get NetworkOnMainThreadException

// Button click
public void onClick(View v) {

    new NetworkOperation().execute();
    dialog.dismiss();
}


private class NetworkOperation extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        String host = "web.vlivetech.com"; //getText(R.id.host);
        String port = "5222";  //getText(R.id.port);
        String service = "web.vlivetech.com"; //getText(R.id.service);
        String username = "khubaib"; //getText(R.id.userid);
        String password = "khubaib"; //getText(R.id.password);

        // Create a connection
        ConnectionConfiguration connConfig =
                new ConnectionConfiguration(host, Integer.parseInt(port));
        XMPPConnection connection = new XMPPConnection(connConfig);

        try {
            connection.connect();
            Log.i("XMPPClient", "[SettingsDialog] Connected to " + connection.getHost());
        } catch (XMPPException ex) {
            Log.e("XMPPClient", "[SettingsDialog] Failed to connect to " + connection.getHost());
            xmppClient.setConnection(null);
        }
        try {
            connection.login(username, password);
            Log.i("XMPPClient", "Logged in as " + connection.getUser());

            // Set the status to available
            Presence presence = new Presence(Presence.Type.available);
            connection.sendPacket(presence);
            xmppClient.setConnection(connection);
        } catch (XMPPException ex) {
            Log.e("XMPPClient", "[SettingsDialog] Failed to log in as " + username);
            xmppClient.setConnection(null);
        }

      return null;
    }

    @Override
    protected void onPostExecute(String result) {

    }
  }


回答2:

This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask. and get this asmack-android-8-0.8.3.jar file to put in your libs. Suggestion: Why don't you write a service for XMPP ?