Android Open Source - mmx-starter-android Main Activity






From Project

Back to project page mmx-starter-android.

License

The source code is released under:

Apache License

If you think the Android project mmx-starter-android listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.magnet.demo.mmx.starter;
/*from   w ww.j ava 2 s .com*/
import java.util.ArrayList;

import com.magnet.mmx.MMXClient;
import com.magnet.mmx.MMXClient.ConnectionEvent;
import com.magnet.mmx.MMXClient.ConnectionInfo;
import com.magnet.mmx.MMXClient.MMXListener;
import com.magnet.mmx.MMXClient.SecurityLevel;
import com.magnet.mmx.client.MMXMessage;
import com.magnet.mmx.client.Options;
import com.magnet.mmx.client.PubSubManager.MMXTopic;
import com.magnet.mmx.util.XIDUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements MMXListener {
  private static final String TAG = MainActivity.class.getSimpleName();

  private EditText mHostField = null;
  private EditText mPortField = null;
  private EditText mUsernameField = null;
  private EditText mPasswordField = null;
  private Button mConnectButton = null;
  private Button mDisconnectButton = null;
  private Button mSendMessageButton = null;
  private CheckBox mSendReceipts = null;
  private TextView mMessageList = null;
  private MMXClient mMMXClient = null;
  private ArrayList<String> mMessageListData = null;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    MyMMXListener.getInstance(this).registerListener(this);

    setContentView(R.layout.activity_main);
    mMessageListData = new ArrayList<String>();

    mMMXClient = MMXClient.getInstance(this, R.raw.quickstart);
    mHostField = (EditText) findViewById(R.id.host);
    mPortField = (EditText) findViewById(R.id.port);
    mUsernameField = (EditText) findViewById(R.id.username);
    mPasswordField = (EditText) findViewById(R.id.password);
    mConnectButton = (Button) findViewById(R.id.btn_connect);
    mDisconnectButton = (Button) findViewById(R.id.btn_disconnect_hard);
    mSendMessageButton = (Button) findViewById(R.id.btn_send_message);
    mSendReceipts = (CheckBox) findViewById(R.id.send_receipts);
    mMessageList = (TextView) findViewById(R.id.message_list);

    //populate fields
    ConnectionInfo connectionInfo = mMMXClient.getConnectionInfo();
    if (connectionInfo.host != null && !connectionInfo.host.isEmpty()) {
      mHostField.setText(connectionInfo.host);
    }
    if (connectionInfo.port >= 0) {
      mPortField.setText(String.valueOf(connectionInfo.port));
    }
    mUsernameField.setText(connectionInfo.username);
    updateButtonState();
  }

  public void onDestroy() {
    MyMMXListener.getInstance(this).unregisterListener(this);
    super.onDestroy();
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      int id = item.getItemId();
      if (id == R.id.action_settings) {
          return true;
      }
      return super.onOptionsItemSelected(item);
  }

  public void doConnect(View v) {
    v.setEnabled(false);
    boolean isConnected = mMMXClient.isConnected();
    Log.d(TAG, "doConnect(): isConnected=" + isConnected);
    if (mMMXClient.isConnected()) {
      //do disconnect
      mMMXClient.disconnect();
    } else {
      //do connect
      boolean hasErrors = false;
      CharSequence host = mHostField.getText();
      CharSequence port = mPortField.getText();
      int portInt = 0;
      CharSequence username = mUsernameField.getText();
      CharSequence password = mPasswordField.getText();

      if (host == null || host.toString().isEmpty()) {
        mHostField.setError(this.getString(R.string.err_host_required));
        hasErrors = true;
      }
      if (port == null || port.toString().isEmpty()) {
        mPortField.setError(this.getString(R.string.err_port_required));
        hasErrors = true;
      } else {
        try {
          portInt = Integer.valueOf(port.toString());
        } catch (NumberFormatException nex) {
          mPortField.setError(this.getString(R.string.err_port_invalid));
          hasErrors = true;
        }
      }
      if (username != null && !username.toString().isEmpty()) {
        //if there's a username, there should be a password
        if (password == null || password.toString().isEmpty()) {
          mPasswordField.setError(this.getString(R.string.err_password_required));
          hasErrors = true;
        }
      } else {
        username = null;
        password = null;
      }
      if (!hasErrors) {
        mMMXClient.connect(host.toString(), portInt,
            username == null ? null : username.toString(),
            password == null ? null : password.toString().getBytes(),
            true, MyMMXListener.getInstance(this), SecurityLevel.NONE);
      } else {
        updateButtonState();
      }
    }
  }

  public void doHardDisconnect(View v) {
    mMMXClient.disconnect(true);
  }

  public void updateButtonState() {
    boolean isFieldsEnabled = true;
    if (mMMXClient.isConnected()) {
      mConnectButton.setText(R.string.label_disconnect);
      mDisconnectButton.setVisibility(View.VISIBLE);
      isFieldsEnabled = false;
    } else {
      mConnectButton.setText(R.string.label_connect);
      mDisconnectButton.setVisibility(View.GONE);
    }
    mHostField.setEnabled(isFieldsEnabled);
    mPortField.setEnabled(isFieldsEnabled);
    mUsernameField.setEnabled(isFieldsEnabled);
    mPasswordField.setEnabled(isFieldsEnabled);
    mSendMessageButton.setEnabled(!isFieldsEnabled);
    mConnectButton.setEnabled(true);
  }

  public void onConnectionEvent(MMXClient client, ConnectionEvent event) {
    Toast.makeText(this, "onConnectionEvent(): " + event, Toast.LENGTH_SHORT).show();
    runOnUiThread(new Runnable() {
      public void run() {
        updateButtonState();
      }
    });
  }

  public void onMessageReceived(MMXClient client, MMXMessage message, String receiptId) {
    Log.d(TAG, "onMessageReceived(): start");
    boolean isReceiptSent = false;
    if (mSendReceipts.isChecked() && receiptId != null) {
      mMMXClient.sendReceipt(receiptId);
      isReceiptSent = true;
    }
    String from = XIDUtil.getUserId(message.getFrom());
    String messageString = (isReceiptSent ? "* " : "") + from + ":  " + message.getPayload().getDataAsString();
    mMessageListData.add(messageString);
    runOnUiThread(new Runnable() {
      public void run() {
        updateMessageListView();
      }
    });
  }

  public void onMessageDelivered(MMXClient client, String recipient, String messageId) {
    AlertDialog dialog = new AlertDialog.Builder(this)
      .setMessage("Message delivered to " + recipient)
      .create();
    dialog.show();
    Ringtone notificationRingtone = RingtoneManager.getRingtone(this, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
    notificationRingtone.play();
  }

  @Override
  public void onPubsubItemReceived(MMXClient client, MMXTopic topic, MMXMessage message) {
    Log.d(TAG, "onPubsubItemReceived(): start");
    String messageString = "TOPIC: " + topic.getTopic() + " FROM: " + message.getFrom() + ":  " + message.getPayload().getDataAsString();
    mMessageListData.add(messageString);
    updateMessageListView();
  }

  public void onSendFailed(MMXClient client, String messageId) {
    AlertDialog dialog = new AlertDialog.Builder(this)
      .setMessage("Message send failure " + messageId)
      .create();
    dialog.show();
  }

  public void doSendMessage(View view) {
    //launch the send message dialog
    DialogFragment newFragment = new SendMessageDialogFragment();
    newFragment.show(getFragmentManager(), "sendMessage");
  }

  public static class SendMessageDialogFragment extends DialogFragment {
    private EditText mToField = null;
    private EditText mMessageField = null;
    private Button mSendButton = null;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      View view = inflater.inflate(R.layout.dialog_send_message, container, true);
      mToField = (EditText) view.findViewById(R.id.to);
      mMessageField = (EditText) view.findViewById(R.id.message);
      mSendButton = (Button) view.findViewById(R.id.btn_send);
      mSendButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
          String to = mToField.getText().toString();
          String message = mMessageField.getText().toString();
          Options options = new Options();
          options.enableReceipt(true);
          MMXClient mmxClient = MMXClient.getInstance(getActivity(), R.raw.quickstart);
          String messageId = mmxClient.sendMessage(new String[] {to},
              "text/plain", "MESSAGE", message, null, options);
          Log.d(TAG, "sendMessage messageId=" + messageId);
        }
      });
      return view;
    }

    public Dialog onCreateDialog(Bundle savedInstanceState) {
      Dialog dialog = super.onCreateDialog(savedInstanceState);
      dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
      return dialog;
    }
  }

  public void updateMessageListView() {
    StringBuilder sb = new StringBuilder();
    int count = 5;
    for (int i = mMessageListData.size(); --i >= 0;) {
      String text = mMessageListData.get(i);
      sb.append(text).append('\n');
      if (--count == 0) {
        break;
      }
    }
    mMessageList.setText(sb.toString());
  }

}




Java Source Code List

com.magnet.demo.mmx.starter.ApplicationTest.java
com.magnet.demo.mmx.starter.MainActivity.java
com.magnet.demo.mmx.starter.MyApplication.java
com.magnet.demo.mmx.starter.MyMMXListener.java
com.magnet.demo.mmx.starter.MyWakeupListener.java