RSS

Category Archives: Android

Get started with RabbitMQ on Android (Android Studio)

By: LOVISA JOHANSSON (cloudamqp)

This guide explains how to create a simple chat application in Android using Android Studio and RabbitMQ. Everyone that has the application will be able to send and receive messages from all other users that are using the same application.

If you are using Eclipse, check out this blog post instead.

In the code given, messages will first be added to an internal queue and the publisher will send messages from the internal queue to RabbitMQ when there is a connection established. The message will be added back to the queue if the connection is broken.

RabbitMQ Android

This guide assumes that you have downloaded, installed and set up everything correct for Android Studio.

Start by creating a new Android project, open Android Studio and go to File -> New -> New Project..

1. Configure your new project

  1. Enter project information as specified below.create new android project
  2. Select the form factor your app will run onandroid studio
  3. Select if you like to add an activity to your app or not. In this example we choose Blank Activity to get autogenerated files for the project.add android activity
  4. Customize the Activitycustomize android activity

2. Add Java AMQP library to project

RabbitMQ has developed an excellent Java AMQP library. The full API documentation for the library can be found here.

We need to include the RabbitMQ Java Client Library and reference the jar files into the project. In Android Studio you can create a libs folder in the same level as the app. Copy and past the jars in to this libs folder. Mark all the jar files and press “Add As Library…” as seen in the image below.

add rabbitmq library

You can confirm that the libs has been added as library by opening build.gradle and check under dependencies, all files should seen be there.

dependencies {
  ...
  compile files('libs/rabbitmq-client.jar')
  ...
}

NOTE: Only if you are using Android Gradle plugin 0.7.0 and do get the error “Duplicate files copied in APK” when you later run your application, you need to add packagingOptions to your build.gradle file as specified in here.

android {
  packagingOptions {
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
  }
}

3. Android Manifest, internet permission

We need to tell the Android system that this app is allowed to access internet. Open the AndroidManifest.xml file, located in the root of the project. Add the user permission android.permission.INTERNET just before the closing /manifest tag.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.cloudamqp.rabbitmq"
     android:versionCode="1"
     android:versionName="1.0">
     ......
     <uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

4. Start coding

Layout

Create the view for the application. The .xml layout file can be found under res->layout. What we have here is a root ScrollView containing a

EditText a Button and a TextView The EditText will be used as an input field for the text that will be sent. The text will be published when the button is pressed and all messages received by the subscriber will be printed to the TextView.

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
  ...
  <EditText
  android:id="@+id/text"
  android:layout_width="fill_parent"
  android:background="#ffffff"
  android:hint="Enter a message" />

  <Button
  android:id="@+id/publish"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_below="@+id/text"
  android:text="Publish message" />

  <TextView
  android:id="@+id/textView"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_below="@+id/publish"
  android:textColor="#000000" />
  ...
</ScrollView>

Publish

Create an internal message queue. In this case is a BlockingDeque used. Blockingqueues implementations are designed to be used primarily for producer-consumer queues.

private BlockingDeque<String> queue = new LinkedBlockingDeque>String>();
void publishMessage(String message) {
  try {
    Log.d("","[q] " + message);
    queue.putLast(message);
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
}

Create a setup function for the ConnectionFactory The connection factory encapsulates a set of connection configuration parameters, in this case the CLOUDAMQP_URL. The URL can be found in the control panel for your instance.

ConnectionFactory factory = new ConnectionFactory();
private void setupConnectionFactory() {
  String uri = "IP";
  try {
    factory.setAutomaticRecoveryEnabled(false);
    //factory.setUri(uri);
    factory.setHost(uri);

  } catch (KeyManagementException | NoSuchAlgorithmException | URISyntaxException e1) {
    e1.printStackTrace();
}

Create a publisher that publish messages from the internal queue. Messages are added back to the queue if an exception is catched. The publisher will try to reconnect every 5 seconds if the connection is broken.

A thread (“background” or “worker” threads or use of the AsyncTask class) is needed when we have operations to perform that are not instantaneous, such as network access when connecting to rabbitMQ.

We will use a fanout exchange. A fanout exchange routes messages to all of the queues that are bound to it and the routing key is ignored. If N queues are bound to a fanout exchange, will a new message that is published to that exchange, be copied and delivered to all N queues. Fanout exchanges are ideal for the broadcast routing of messages.

public void publishToAMQP()
{
  publishThread = new Thread(new Runnable() {
    @Override
    public void run() {
      while(true) {
        try {
          Connection connection = factory.newConnection();
          Channel ch = connection.createChannel();
          ch.confirmSelect();

          while (true) {
            String message = queue.takeFirst();
            try{
              ch.basicPublish("amq.fanout", "chat", null, message.getBytes());
              Log.d("", "[s] " + message);
              ch.waitForConfirmsOrDie();
            } catch (Exception e){
              Log.d("","[f] " + message);
              queue.putFirst(message);
              throw e;
           }
         }
       } catch (InterruptedException e) {
         break;
       } catch (Exception e) {
         Log.d("", "Connection broken: " + e.getClass().getName());
         try {
           Thread.sleep(5000); //sleep and then try again
         } catch (InterruptedException e1) {
           break;
         }
       }
     }
   }
  });
  publishThread.start();
}

Subscriber

We have now created the publisher, and it is time to create the subscriber. The subscriber will take a handler as parameter. The handler will print the messages to the screen when the messages arrives. The subscribe thread will try to reconnect every 5 seconds when the connection gets broken.

void subscribe(final Handler handler)
{
  subscribeThread = new Thread(new Runnable() {
    @Override
    public void run() {
      while(true) {
        try {
          Connection connection = factory.newConnection();
          Channel channel = connection.createChannel();
          channel.basicQos(1);
          DeclareOk q = channel.queueDeclare();
          channel.queueBind(q.getQueue(), "amq.fanout", "chat");
          QueueingConsumer consumer = new QueueingConsumer(channel);
          channel.basicConsume(q.getQueue(), true, consumer);

          while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            Log.d("","[r] " + message);
            Message msg = handler.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString("msg", message);
            msg.setData(bundle);
            handler.sendMessage(msg);
          }
        } catch (InterruptedException e) {
          break;
        } catch (Exception e1) {
          Log.d("", "Connection broken: " + e1.getClass().getName());
          try {
            Thread.sleep(5000); //sleep and then try again
          } catch (InterruptedException e) {
            break;
          }
        }
      }
    }
  });
  subscribeThread.start();
}

Call all functions listed above from function onCreate The handler used by the subscribe functions is also created in onCreate. A handler has to be used because it is only possible to write to the GUI from the main tread.

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  setupConnectionFactory();
  publishToAMQP();
  setupPubButton();

  final Handler incomingMessageHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      String message = msg.getData().getString("msg");
      TextView tv = (TextView) findViewById(R.id.textView);
      Date now = new Date();
      SimpleDateFormat ft = new SimpleDateFormat ("hh:mm:ss");
      tv.append(ft.format(now) + ' ' + message + '\n');
    }
  };
  subscribe(incomingMessageHandler);
}

void setupPubButton() {
  Button button = (Button) findViewById(R.id.publish);
  button.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View arg0) {
      EditText et = (EditText) findViewById(R.id.text);
      publishMessage(et.getText().toString());
      et.setText("");
   }
  });
}

The subscribe and the publish tread can both be interrupted when the application is destroyed by adding following code in onDestroy

Thread subscribeThread;
Thread publishThread;
@Override
protected void onDestroy() {
  super.onDestroy();
  publishThread.interrupt();
  subscribeThread.interrupt();
}

 

Copy from: https://www.cloudamqp.com/blog/2015-07-29-rabbitmq-on-android.html

 

Android support multidex library implementation

By: Nicolas Tyler

There are a few things you have to do,

1- In your gradle you need to specify multidex and add the support library:

android {
    defaultConfig {
        ...
        multiDexEnabled true
        ...
    }
}

dependencies {
  ...
  compile 'com.android.support:multidex:1.0.0'
  ...
}

2- In your manifest you have to set your application to a multidex application:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.package.name">
    <application
        ...
        android:name="com.package.name.my_application">
        ...
    </application>
</manifest>

3.1- In your application class you have to either extend MultiDexApplication:

public class my_application extends MultiDexApplication
{
    ...
}

3.2- Or Overide the attachBaseContext() method:

public class my_application extends Application
{
    protected void attachBaseContext(Context base)
    {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}

Copy from: http://stackoverflow.com/questions/26925264/android-support-multidex-library-implementation

 
Leave a comment

Posted by on August 25, 2015 in Android, Mobile Development

 

Integrated aSmack (Openfire) with Android

By: http://developer.samsung.com/

Introduction

Instant messaging (IM) communication is done through the use Extensible Messaging and Presence Protocol (XMPP) (also known as Jabber), an open standard XML based messaging communication protocol.

Most IM Clients use the XMPP protocol for communication. Google is one of the clients that use XMPP for its Google Talk Product.

There are various third party libraries available for developing Instant Messaging client applications. One of the most popular XMPP client libraries is Smack API, which is a pure Java Library which allows developers to create IM Clients. Following is a walkthrough of building a simple chat application using the Smack API.

Before starting to develop and explore some of the features of Smack API, developers are requested to go through the technical documentation and API documentation of Smack API (3.2.2 latest version at this time of development of this article)

SmackAPI

The Smack API is a pure Java Library. The asmack third party library has heavily patched the Smack API to work with Android. For more information, visit the Smack API community thread.

Libraries are available under the following section:

Download the asmack library jar file with naming convention asmack-<date>.jar, where <date> is the date of release. Add it to your project lib folder.

The sample chat application does the following:

  • Connects to a GTalk Server
  • Logs into GTalk Server
  • Sets user Presence
  • Gets Rosters
  • Sends Messages
  • Receives Messages

 

Connecting to a Server

In this document, Google Talk Server is used for the development of sample chat app.

Connecting to XMPP server requires knowing of configuration parameters set by XMPP Server.

Following are the required configuration parameters for connecting to GTalk Server:

public static final String HOST = "talk.google.com";
public static final int PORT = 5222;
public static final String SERVICE = "gmail.com";

[Code 1]

For more information on configuration parameters, visit GTalk Developers site.

Following code snippet shows how to use the Smack API for connecting to XMPP Server

ConnectionConfiguration connConfig = new ConnectionConfiguration(HOST, PORT, SERVICE);
XMPPConnection connection = new XMPPConnection(connConfig);

try {
  //Connect to the server
  connection.connect();
} catch (XMPPException ex) {
  connection = null;
  //Unable to connect to server
}

[Code 2]

The XMPPConnection class is used to create the connection to the XMPP server specified by the ConnectionConfiguration class, which uses configuration parameters for establishing connection with the server.

To disconnect, use the disconnect() method.

Login to a Server

Once a connection is established, the user should log in with username and password using the login() method of the Connection class. Following code snippet shows how to login:

//Most servers require you to login before performing other tasks.
connection.login(USERNAME, PASSWORD);
//for example: connection.login(“abc@gmail.com”, “password”);

[Code 3]

Once logged in, user can start using chat features; Chat or GroupChats, Set Presence, Get Rosters etc.

Setting user Presence

After logging in, the user might set his or her presence (availability) status visible to other recipients (Rosters) present in the chat list.

The following code shows how to set the presence. The Presence object is created with a status set to type “unavailable”. This presence status is later send as packet using the Connection class’s sendPacket() method.

// Create a new presence. Pass in false to indicate we're unavailable.
Presence presence = new Presence(Presence.Type.unavailable);
presence.setStatus("I’m unavailable");
connection.sendPacket(presence);

[Code 4]

Getting Roster

The Roster class does the following

  • Keeps track of the availability (presence) of other users
  • Allows users to be organized into groups such as “Friends” and “Co-workers”
  • Finds all roster entries and groups they belong to
  • Retrieves the presence status of each user.

Retrieving the roster is done using the Connection.getRoster() method.

Roster roster = connection.getRoster();
//Get all rosters
Collection<RosterEntry> entries = roster.getEntries();
//loop through
for (RosterEntry entry : entries) {
//example: get presence, type, mode, status
Presence entryPresence = roster.getPresence(entry.getUser());
  Presence.Type userType = entryPresence.getType();
  Presence.Mode mode = entryPresence.getMode();
  String status = entryPresence.getStatus();
}

[Code 5]

The previous code provides the status of users at a given point in time, but to obtain users’ Presence in real time, RosterListener (interface) is used. The Callback methods are called whenever there is change in roster or change in the presence of users in the roster.

roster.addRosterListener(new RosterListener() {
 @Override
 public void presenceChanged(Presence presence) {
   //Called when the presence of a roster entry is changed
 }
 @Override
 public void entriesUpdated(Collection<String> arg0) {
   // Called when a roster entries are updated.
 }
 @Override
 public void entriesDeleted(Collection<String> arg0) {
   // Called when a roster entries are removed.
 }
@Override
 public void entriesAdded(Collection<String> arg0) {
   // Called when a roster entries are added.
 }
});

[Code 6]

Sending Messages

Messages can be sent in one of two ways:

  • In the form of packets using XMPPConnection sendPacket(Message msg) method.
  • As a string of Chat Messages using the Chat class. The Chat is a series of messages exchange between two or more users.

Following code snippet shows how to send Message using sendPacket() method of XMPPConnection

// Send chat msg to with msg type as (chat, normal, groupchat, headline, error)
Message msg = new Message(String to, Message.Type type);
msg.setBody(“How are you?”);
connection.sendPacket(msg);

[Code 7]

The chat class is a convenient way to send messages. The following code snippet shows how to send message using Chat class.

ChatManager chatmanager = connection.getChatManager();
Chat newChat = chatmanager.createChat("abc@gmail.com", new MessageListener() {
  // Receiving Messages
  public void processMessage(Chat chat, Message message) {
    Message outMsg = new Message(message.getBody());
    try {
      //Send Message object
      newChat.sendMessage(outMsg);
    } catch (XMPPException e) {
      //Error
    }
  }
});
try {
  //Send String as Message
  newChat.sendMessage("How are you?");
} catch (XMPPException e) {
  //Error
}

[Code 8]

The ChatManager instance is obtained from XMPPConnection using the getChatManager() method. ChatManager keeps track on all current chats. Chat is created which will now be series of messages exchanged between two users.

The sendMessage(String msg) or sendMessage(Message msg) method is used for sending text messages or message object in the context of a given chat session.

Moreover, MessageListener can be used to get callbacks of notification of Message from other users on chat.

Receiving Messages

Receiving messages from other user is done using:

  • Poll mechanism provided through the use of the PacketCollector class.
  • Asynchronous mechanism through the use of the PacketListener (Recommended)

The following code snippet shows an asynchronous way of listening to incoming messages using PacketListener.

// 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;
    String body = message.getBody();
    String from = message.getFrom();
  }
}, filter);

[Code 9]

Sample Example

Here an example consists of ListView to display the chat conversation between two users. It has by default set values of Google talk XMPP parameters.

Remember to add the jar file into your project lib folder and Internet permission in manifest file. The example is using the asmack library: patched version made for Android.

res\layout\main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical" >

  <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:minWidth="70dp"
      android:text="Chat With"
      android:textStyle="bold" />

    <EditText
      android:id="@+id/toET"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:hint="Add Recipient"
      android:minWidth="250dp"
      android:scrollHorizontally="true"
      android:singleLine="true"
      android:textSize="16sp" />
  </LinearLayout>

  <ListView
    android:id="@+id/listMessages"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:scrollbars="horizontal" />

  <LinearLayout
    android:id="@+id/linearLayout2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="bottom"
    android:orientation="horizontal" >

    <EditText
      android:id="@+id/chatET"
      android:layout_width="0dip"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:gravity="top"
      android:hint="Type to compose"
      android:scrollHorizontally="true" >
    </EditText>

    <Button
      android:id="@+id/sendBtn"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginLeft="5dp"
      android:layout_marginRight="5dp"
      android:layout_marginTop="5dp"
      android:text="Send"
      android:textStyle="bold" />
  </LinearLayout>
</LinearLayout>

[Code 10]

res\layout\listitem.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/text1"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:singleLine="false"
  android:textStyle="bold" />

[Code 11]

AndroidManifest.xml
"<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.demo.xmppchat"
  android:versionCode="1"
  android:versionName="1.0" >

  <uses-sdk android:minSdkVersion="8" />

  <uses-permission android:name="android.permission.INTERNET" />

  <application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
      android:name=".XMPPChatDemoActivity"
      android:label="@string/app_name" >
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
  </application>

</manifest>

[Code 12]

XMPPChatDemoActivity.java
package com.demo.xmppchat;

import java.util.ArrayList;
import java.util.Collection;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.util.StringUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class XMPPChatDemoActivity extends Activity {

  public static final String HOST = "talk.google.com";
  public static final int PORT = 5222;
  public static final String SERVICE = "gmail.com";
  public static final String USERNAME = "userid@gmail.com";
  public static final String PASSWORD = "password";

  private XMPPConnection connection;
  private ArrayList<String> messages = new ArrayList<String>();
  private Handler mHandler = new Handler();

  private EditText recipient;
  private EditText textMessage;
  private ListView listview;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    recipient = (EditText) this.findViewById(R.id.toET);
    textMessage = (EditText) this.findViewById(R.id.chatET);
    listview = (ListView) this.findViewById(R.id.listMessages);
    setListAdapter();

    // Set a listener to send a chat text message
    Button send = (Button) this.findViewById(R.id.sendBtn);
    send.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        String to = recipient.getText().toString();
        String text = textMessage.getText().toString();          
        Log.i("XMPPChatDemoActivity ", "Sending text " + text + " to " + to);
        Message msg = new Message(to, Message.Type.chat);  
        msg.setBody(text);
        if (connection != null) {
          connection.sendPacket(msg);
          messages.add(connection.getUser() + ":");
          messages.add(text);
          setListAdapter();
        }
      }
    });
    connect();
  }

  /**
   * Called by Settings dialog when a connection is establised with 
   * the XMPP server
   */
  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() {
        @Override
        public void processPacket(Packet packet) {
          Message message = (Message) packet;
          if (message.getBody() != null) {
            String fromName = StringUtils.parseBareAddress(message.getFrom());
            Log.i("XMPPChatDemoActivity ", " Text Recieved " + 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, R.layout.listitem, messages);
    listviewr.setAdapter(adapter);
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    try {
      connection.disconnect();
    } catch (Exception e) {

    }
  }

  public void connect() {

    final ProgressDialog dialog = ProgressDialog.show(this, "Connecting...", "Please wait...", false);
    Thread t = new Thread(new Runnable() {
      @Override
      public void run() {
        // Create a connection
       ConnectionConfiguration connConfig = new ConnectionConfiguration(HOST, PORT, SERVICE);
       XMPPConnection connection = new XMPPConnection(connConfig);
         try {
           connection.connect();
           Log.i("XMPPChatDemoActivity",  "[SettingsDialog] Connected to "+connection.getHost());
         } catch (XMPPException ex) {
             Log.e("XMPPChatDemoActivity",  "[SettingsDialog] Failed to connect to "+ connection.getHost());
             Log.e("XMPPChatDemoActivity", ex.toString());
             setConnection(null);
         }
          try {
            connection.login(USERNAME, PASSWORD);
            Log.i("XMPPChatDemoActivity",  "Logged in as" + connection.getUser());

            // Set the status to available
            Presence presence = new Presence(Presence.Type.available);
            connection.sendPacket(presence);
            setConnection(connection);

            Roster roster = connection.getRoster();
            Collection<RosterEntry> entries = roster.getEntries();
            for (RosterEntry entry : entries) {

              Log.d("XMPPChatDemoActivity",  "--------------------------------------");
              Log.d("XMPPChatDemoActivity", "RosterEntry " + entry);
              Log.d("XMPPChatDemoActivity", "User: " + entry.getUser());
              Log.d("XMPPChatDemoActivity", "Name: " + entry.getName());
              Log.d("XMPPChatDemoActivity", "Status: " + entry.getStatus());
              Log.d("XMPPChatDemoActivity", "Type: " + entry.getType());
              Presence entryPresence = roster.getPresence(entry.getUser());

              Log.d("XMPPChatDemoActivity", "Presence Status: "+ entryPresence.getStatus());
              Log.d("XMPPChatDemoActivity", "Presence Type: " + entryPresence.getType());

              Presence.Type type = entryPresence.getType();
              if (type == Presence.Type.available)
                Log.d("XMPPChatDemoActivity", "Presence AVIALABLE");
                Log.d("XMPPChatDemoActivity", "Presence : " + entryPresence);
              }
              } catch (XMPPException ex) {
                Log.e("XMPPChatDemoActivity", "Failed to log in as "+  USERNAME);
                Log.e("XMPPChatDemoActivity", ex.toString());
                setConnection(null);
              }
              dialog.dismiss();
           }
      });
    t.start();
    dialog.show();
  }
}

Copy from: http://developer.samsung.com/technical-doc/view.do;jsessionid=pgvxVGNDSLFfXznD9vvnMm0h0JQKhpJhpJvsVlgMK6vdx1R0NxWQ!-1892717541?v=T000000119

 
2 Comments

Posted by on August 7, 2015 in Android, Mobile Development, XMPP

 

Compile Google Volley to JAR on Windows

By Sochinda,

Requirement:

1-Install Git
Go to: https://git-scm.com/download/win
and install

3-JDK
PATH: C:\Program Files\Java\jdk1.7.0_75\bin
JAVA_HOME: C:\Program Files\Java\jdk1.7.0_75

3-Android Command
Open Android Studio
File -> Project Stucture -> check SDK location
– add …\tools;…\platform-tools in PATH
4-Apache Ant
Go to: https://ant.apache.org/bindownload.cgi -> and click download file zip
Extract and copy to path as C:\apache-ant-1.9.6 (Example)
And Add to the last
PATH: C:\apache-ant-1.9.6\bin;

Step:
Open command prompt and type the bellow command:

$ git clone https://android.googlesource.com/platform/frameworks/volley
$ cd volley
$ android update project -p .
$ ant jar

 
Leave a comment

Posted by on July 10, 2015 in Android, Mobile Development

 

Set transparent background of an imageview in Android

How to calculate transparent color in Android with 8 digit format (#xxxxxxxx):

Ex we want to use only 50% of background color

x = 50/100 * 255 = 127.5 => x = 127 and convert 127 from decimal to hexadecimal

=> x (hex) = 7F.

Finnaly => 50% => #7F000000

 

Referenced by: http://stackoverflow.com/questions/1492554/set-transparent-background-of-an-imageview-in-android

 
Leave a comment

Posted by on January 29, 2015 in Android, Mobile Development

 

Android: Speech To Text Using API

By 

Android has a very cool feature that still many developers dont know. Apps like Any.DO uses speech to text conversion feature quite creatively. In today’s world of Siri, voice commands are of utmost importance. Android natively provides feature of Speech to Text so why not to use it in our app!

I will show you how to use Android’s Speech to Text API in an application.

Let’s make our demo application.

Demo App

The App will be very simple. It will have a button with Mic symbol. On click of which we trigger Android’s Speech to Text Intent which shows a dialog to take speech input. The speech input is then converted into text. The text is then displayed in a text view.

Step 1: Create Basic Android Project in Eclipse

Create a Hello World Android project in Eclipse. Go to New > Project > Android Project. Give the project name as SpeechToTextDemo and select Android Runtime 2.1 or sdk 7. I have given package name net.viralpatel.android.speechtotextdemo.

Once you are done with above steps, you will have a basic hello world Android App.

Step 2: Change the Layout

For our demo, we need simple layout. Just one Image Button to trigger Speech to Text API and one TextView to display result text that is converted from speech.

Open layout/main.xml in your android project and replace its content with following:

File: res/layout/main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/textView1"
    android:layout_toLeftOf="@+id/textView1"
    android:gravity="center"
    android:orientation="vertical" >
    <ImageButton
        android:id="@+id/btnSpeak"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:contentDescription="@string/speak"
        android:src="@android:drawable/ic_btn_speak_now" />
    <TextView
        android:id="@+id/txtText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>

The UI is very simply. One LinearLayout to organize the button and text view. Note the id for button:btnSpeak and text view: txtText which we will use in our Java code.

Step 3: Android Java Code to trigger Speech to Text API

Open SpeechToTextDemoActivity class and replace the code with following.

File: SpeechToTextDemoActivity.java

package net.viralpatel.android.speechtotextdemo;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
    protected static final int RESULT_SPEECH = 1;
    private ImageButton btnSpeak;
    private TextView txtText;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtText = (TextView) findViewById(R.id.txtText);
        btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
        btnSpeak.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(
                        RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
                try {
                    startActivityForResult(intent, RESULT_SPEECH);
                    txtText.setText("");
                } catch (ActivityNotFoundException a) {
                    Toast t = Toast.makeText(getApplicationContext(),
                            "Opps! Your device doesn't support Speech to Text",
                            Toast.LENGTH_SHORT);
                    t.show();
                }
            }
        });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
        case RESULT_SPEECH: {
            if (resultCode == RESULT_OK && null != data) {
                ArrayList<String> text = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                txtText.setText(text.get(0));
            }
            break;
        }
        }
    }
}

The heart of Speech to text Android API is package android.speech and specifically classandroid.speech.RecognizerIntent. Basically we trigger an Intent (android.speech.RecognizerIntent) which shows dialog box to recognize speech input. This Activity then converts the speech into text and send backs the result to our calling Activity. When we invoke android.speech.RecognizerIntent intent, we must use startActivityForResult() as we must listen back for result text.

Note how in above code we crate intent android.speech.RecognizerIntent and trigger it. Also we add one extra parameter using .putExtra() method. When invoking RecognizerIntent, we must provide extraRecognizerIntent.EXTRA_LANGUAGE_MODE. Here we are setting its value to en-US.

Since we triggered the RecognizerIntent via startActivityForResult(), we override methodonActivityResult(int requestCode, int resultCode, Intent data) to handle the result data. The
RecognizerIntent will convert the speech input to text and send back the result as ArraList with key RecognizerIntent.EXTRA_RESULTS. Generally this list should be ordered in descending order of speech recognizer confidence. Only present when RESULT_OK is returned in an activity result. We just set the text that we got in result in text view txtText using txtText.setText().

One thing worth noting here is how to handle devices/android version that doesn’t support speech to text API. In such case, exception ActivityNotFoundException will be thrown when we try to start activity. In above example, we have catched this exception and displayed a message “Opps! Your device doesn’t support Speech to Text” using Toast.

Screen shots of Android App

And that’s all! Just execute the app in Android emulator or real device and see following output.

android-speech-to-text-api-demo

android-speech-to-text-activity

android-speech-to-text-conversion

android-speech-text

Download Source Code

Android_SpeechToTextDemo.zip (350 KB)

References

RecognizerIntent.html#ACTION_RECOGNIZE_SPEECH Documentation

Copy from: http://viralpatel.net/blogs/android-speech-to-text-api/

 
1 Comment

Posted by on April 30, 2014 in Android, Mobile Development

 

Run Android on The Real Device

Using Hardware Devices

When building a mobile application, it’s important that you always test your application on a real device before releasing it to users. This page describes how to set up your development environment and Android-powered device for testing and debugging on the device.

You can use any Android-powered device as an environment for running, debugging, and testing your applications. The tools included in the SDK make it easy to install and run your application on the device each time you compile. You can install your application on the device directly from Eclipse or from the command line with ADB. If you don’t yet have a device, check with the service providers in your area to determine which Android-powered devices are available.

If you want a SIM-unlocked phone, then you might consider a Nexus phone. To purchase a Nexus phone, visit the Google Play store.

Note: When developing on a device, keep in mind that you should still use the Android emulator to test your application on configurations that are not equivalent to those of your real device. Although the emulator does not allow you to test every device feature (such as the accelerometer), it does allow you to verify that your application functions properly on different versions of the Android platform, in different screen sizes and orientations, and more.

Setting up a Device for Development


With an Android-powered device, you can develop and debug your Android applications just as you would on the emulator. Before you can start, there are just a few things to do:

  1. Declare your application as “debuggable” in your Android Manifest.When using Eclipse, you can skip this step, because running your app directly from the Eclipse IDE automatically enables debugging.

    In the AndroidManifest.xml file, add android:debuggable="true" to the <application> element.

    Note: If you manually enable debugging in the manifest file, be sure to disable it before you build for release (your published application should usually not be debuggable).

  2. Enable USB debugging on your device.
    • On most devices running Android 3.2 or older, you can find the option under Settings > Applications > Development.
    • On Android 4.0 and newer, it’s in Settings > Developer options.

      Note: On Android 4.2 and newer, Developer options is hidden by default. To make it available, go to Settings > About phone and tap Build number seven times. Return to the previous screen to find Developer options.

  3. Set up your system to detect your device.
    • If you’re developing on Windows, you need to install a USB driver for adb. For an installation guide and links to OEM drivers, see the OEM USB Drivers document.
    • If you’re developing on Mac OS X, it just works. Skip this step.
    • If you’re developing on Ubuntu Linux, you need to add a udev rules file that contains a USB configuration for each type of device you want to use for development. In the rules file, each device manufacturer is identified by a unique vendor ID, as specified by the ATTR{idVendor} property. For a list of vendor IDs, see USB Vendor IDs, below. To set up device detection on Ubuntu Linux:
      1. Log in as root and create this file: /etc/udev/rules.d/51-android.rules.Use this format to add each vendor to the file:
        SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666", GROUP="plugdev"

        In this example, the vendor ID is for HTC. The MODE assignment specifies read/write permissions, and GROUPdefines which Unix group owns the device node.

        Note: The rule syntax may vary slightly depending on your environment. Consult the udev documentation for your system as needed. For an overview of rule syntax, see this guide to writing udev rules.

      2. Now execute:
        chmod a+r /etc/udev/rules.d/51-android.rules

Note: When you connect a device running Android 4.2.2 or higher to your computer, the system shows a dialog asking whether to accept an RSA key that allows debugging through this computer. This security mechanism protects user devices because it ensures that USB debugging and other adb commands cannot be executed unless you’re able to unlock the device and acknowledge the dialog. This requires that you have adb version 1.0.31 (available with SDK Platform-tools r16.0.1 and higher) in order to debug on a device running Android 4.2.2 or higher.

When plugged in over USB, you can verify that your device is connected by executing adb devices from your SDKplatform-tools/ directory. If connected, you’ll see the device name listed as a “device.”

If using Eclipse, run or debug your application as usual. You will be presented with a Device Chooser dialog that lists the available emulator(s) and connected device(s). Select the device upon which you want to install and run the application.

If using the Android Debug Bridge (adb), you can issue commands with the -d flag to target your connected device.

USB Vendor IDs

This table provides a reference to the vendor IDs needed in order to add USB device support on Linux. The USB Vendor ID is the value given to the ATTR{idVendor} property in the rules file, as described above.

Company USB Vendor ID
Acer 0502
ASUS 0b05
Dell 413c
Foxconn 0489
Fujitsu 04c5
Fujitsu Toshiba 04c5
Garmin-Asus 091e
Google 18d1
Haier 201E
Hisense 109b
HTC 0bb4
Huawei 12d1
K-Touch 24e3
KT Tech 2116
Kyocera 0482
Lenovo 17ef
LG 1004
Motorola 22b8
MTK 0e8d
NEC 0409
Nook 2080
Nvidia 0955
OTGV 2257
Pantech 10a9
Pegatron 1d4d
Philips 0471
PMC-Sierra 04da
Qualcomm 05c6
SK Telesys 1f53
Samsung 04e8
Sharp 04dd
Sony 054c
Sony Ericsson 0fce
Teleepoch 2340
Toshiba 0930
ZTE 19d2
 
Leave a comment

Posted by on April 28, 2014 in Android, Mobile Development