2011年5月20日金曜日

AndroidStudyMemo=Using the Google API with GTalk

Configuring the Android Emulator for GTalk

Before you can begin coding this project, you need to adjust a development setting on the

Android Emulator, XMPP Settings.

 

With the project open, you need to depart from your routine for a minute. If you are

familiar with GTalk, you are aware that you can use the product only when you log into

your Google account. Therefore, you must take an extra step now to ensure that your

device (in this case, the Android Emulator) can log into your Google account, thus

enabling you to send and receive messages.

 

Navigate to your AndroidSDK/tools folder and launch the Emulator. You could

launch it from within the Eclipse development environment, but that would require

you to also launch an Activity that you have not coded yet. To save some time, just

launch the Emulator manually.

 

After the Emulator is open, click the All shortcut. Find the Dev Tools item and launch

it.Scroll through the Dev Tools menu until you find XMPP Settings.

 

You need to add the login information for your Google account to allow your Activity

access to Google's servers.

 

 

Implementing GTalk in Android

In this section you will use the Google API to create a GTalk-enabled Activity. This

Activity will send and receive messages from the GTalk network, save them on screen,

and display them in a notification bar. Your Activity will be able to communicate with

other GTalk users, whether they are using GTalk on an Android phone or the PC.

 

 

Creating the Activity's Layout in the GoogleAPI.xml

This Activity consists of several Views. You need a ListView to display your text

messages as you send and receive them. You also need two EditText Views, for the

recipient's address and the message, and a Button for the send function.

First, set up a ListView with the id of messageList, as follows. You will be using a

new attribute in this layout, android:scrollbars. Setting this attribute to vertical gives you

a way to scroll through the message list.

 

Place this ListView in the main layout tag. Under the ListView layout, place the

layout for an EditText, as follows. This EditText will hold the address of the recipient

that you are messaging.

 

There should be nothing out of the ordinary with this EditText View.

Finally, you need to create a new horizontal layout to hold the message contents,

EditText View, and the Send Button.

 

This layout will line up your Views so that they fall inline with each other. Place

this LinearLayout in your main LinearLayout. Your final GoogleAPI.xml file should

look like this:

             

              <?xml version="1.0" encoding="utf-8"?>

              <LinearLayout

                            xmlns:android="http://schemas.android.com/apk/res/android"

                            android:orientation="vertical"

                            android:layout_width="fill_parent"

                            android:layout_height="fill_parent">

 

                            <ListView

                                          android:id="@+id/messageList"

                                          android:layout_width="fill_parent"

                                          android:layout_height="0dip"

                                          android:scrollbars="vertical"

                                          android:layout_weight="1"

                                          android:drawSelectorOnTop="false" />

 

                            <EditText

                                          android:id="@+id/messageTo"

                                          android:layout_width="wrap_content"

                                          android:layout_height="wrap_content"

                                          android:textSize="16sp"

                                          android:minWidth="250dp"

                                          android:scrollHorizontally="true" />

 

                            <LinearLayout

                                          xmlns:android="http://schemas.android.com/apk/res/android"

                                          android:orientation="horizontal"

                                          android:layout_width="fill_parent"

                                          android:layout_height="wrap_content">

 

                                          <EditText

                                                        android:id="@+id/messageText"

                                                        android:layout_width="wrap_content"

                                                        android:layout_height="wrap_content"

                                                        android:textSize="16sp"

                                                        android:minWidth="250dp"

                                                        android:scrollHorizontally="true" />

                                          <Button

                                                        android:id="@+id/btnSend"

                                                        android:layout_width="wrap_content"

                                                        android:layout_height="wrap_content"

                                                        android:text="Send Msg">

                                          </Button>

                            </LinearLayout>

              </LinearLayout>

 

 

Adding Packages to GoogleAPI.java

With the layout file complete, there are a number of new packages you need to add to

GoogleAPI.java. The first packages that you must import correspond to the Views you

added to the layout. Therefore, you must import the packages for the EditText, ListView,

ListAdapter, and Button:

              import android.widget.EditText;

              import android.widget.ListView;

              import android.widget.ListAdapter;

              import android.widget.Button;

 

You also need to import the packages of the Google API that deal with GTalk:

              import com.google.android.gtalkservice.IGTalkSession;

              import com.google.android.gtalkservice.IGTalkService;

              import com.google.android.gtalkservice.GTalkServiceConstants;

              import com.google.android.gtalkservice.IChatSession;

 

Some other packages that you need in this application include Intent,

ServiceConnection, Color, and Im. The full list is as follows:

              import android.content.ComponentName;

              import android.content.Intent;

              import android.content.ServiceConnection;

              import android.database.Cursor;

              import android.os.Bundle;

              import android.os.DeadObjectException;

              import android.os.IBinder;

              import android.provider.Im;

              import android.graphics.Color;

              import android.view.View;

              import android.widget.SimpleCursorAdapter;

 

As you can see, quite a few packages are needed for this Activity. However, as you

will find, the amount of code needed to send and receive a message is relatively small.

Now you need to implement an OnClickListener that will run your code.

 

Implementing the View.OnClickListener

You need to modify the GoogleAPI class to implement the View.OnClickListener. This

will allow you to call the onClick( ) method from the Activity's main class when any

button is clicked. Normally, this way of implementing the onClick( ) method is only

effective when you have numerous buttons on one Activity and want to handle all the

onClick calls in one method. However, I felt that you should still see how the method

works so you can use it in your own future code. Keep in mind that I am showing this

method because it can be a valuable tool in many situations.

              public class GoogleAPI extends Activity implements View.OnClickListener {

              }

 

Implementing general variables in your Activity is another concept that hasn't been

covered previously in this book. You need to establish in this Activity a few general

variables that you can work with from multiple methods:

              EditText messageText;

              ListView messageList;

              IGTalkSession myIGTalkSession;

              EditText messageTo;

              Button sendButton;

 

In your onCreate( ) method, you will perform your normal initializations. You

should assign your layouts to your Views and set IGTalkSession to null. Also, just

to add a little bit of interest to your Activity, change the background color of the

ListView to gray.

              myIGTalkSession = null;

              messageText = (EditText) findViewById(R.id.messageText);

              messageList = (ListView) findViewById(R.id.messageList);

              messageTo = (EditText) findViewById(R.id.messageTo);

              sendButton = (Button) findViewById(R.id.btnSend);

              sendButton.setOnClickListener(this);

              messageList.setBackgroundColor(Color.GRAY );

 

The final piece of business to perform in the onCreate( ) method is to bind your

service. This process creates the connection that you will use, facilitated by the Google

account you established in the Dev Tools, to pass your GTalk messages:

              this.bindService(new

                            Intent().setComponent(GTalkServiceConstants.GTALK_SERVICE_COMPONENT),

                                          connection, 0);

 

In the bindService statement above, one of the parameters you pass to the setComponent( )

method is connection. This variable represents a ServiceConnection that implements the

onServiceConnected( ) and onServiceDisconnected( ) methods. The following code builds

the connection that is bound in the previous bindService statement:

              private ServiceConnection connection = new ServiceConnection() {

                            public void onServiceConnected(ComponentName name, IBinder service) {

                                          try {

                                                        myIGTalkSession =

                                                                      IGTalkService.Stub.asInterface(service).getDefaultSession();

                                          } catch (DeadObjectException e) {

                                                        myIGTalkSession = null;

                                          }

                            }

 

                            public void onServiceDisconnected(ComponentName name) {

                                          myIGTalkSession = null;

                            }

              };

 

In the onServiceConnected( ) method, you establish a session using the

IGTalkService.Stub. If this process fails, you should set the session to null once again.

Similarly, in the onServiceDisconnected( ) method, you set the session to null.

 

Now you can create the code for the class's onClick event. There are several actions

that you should perform during each onClick event:

              1. Check the database for any messages.

              2. Create a ListAdapter from the results of this query and display them to the ListView.

              3. Create a ChatSession to the address in the EditView and send your message text.

 

The following line of code queries the database for any messages sent between you

and the messageTo recipient:

              Cursor cursor = managedQuery(Im.Messages.CONTENT_URI, null,

              "contact=\'" + messageTo.getText().toString() + "\'", null, null);

 

Use the following code to create a ListAdapter from the query results and assign the

adapter to the ListView. You have used a similar process in a previous Activity, so it

should not look foreign to you.

              ListAdapter adapter = new SimpleCursorAdapter(this,

                            android.R.layout.simple_list_item_1, cursor,

                            new String[]{Im.MessagesColumns.BODY},

                            new int[]{android.R.id.text1});

              this.messageList.setAdapter(adapter);

 

With the messages displayed, the last step is to send your message. The following

lines of code create an IChatSession with the specified messageTo address. The message

text is then passed over this session to the recipient.

              try {

                            IChatSession chatSession;

                            chatSession =

                                          myIGTalkSession.createChatSession(messageTo.getText().toString(););

 

                            chatSession.sendTextMessage(messageText.getText().toString());

              } catch (DeadObjectException ex) {

                            myIGTalkSession = null;

              }

 

When you put it all together, the complete GoogleAPI.java file should look like this:

package android_programmers_guide.GoogleAPI;

              import android.app.Activity;

              import android.content.ComponentName;

              import android.content.Intent;

              import android.content.ServiceConnection;

              import android.database.Cursor;

              import android.os.Bundle;

              import android.os.DeadObjectException;

              import android.os.IBinder;

              import android.provider.Im;

              import android.graphics.Color;

              import android.view.View;

              import android.widget.EditText;

              import android.widget.ListView;

              import android.widget.ListAdapter;

              import android.widget.Button;

              import android.widget.SimpleCursorAdapter;

              import com.google.android.gtalkservice.IGTalkSession;

              import com.google.android.gtalkservice.IGTalkService;

              import com.google.android.gtalkservice.GTalkServiceConstants;

              import com.google.android.gtalkservice.IChatSession;

 

              public class GoogleAPI extends Activity implements View.OnClickListener {

                            EditText messageText;

                            ListView messageList;

                            IGTalkSession myIGTalkSession;

                            EditText messageTo;

                            Button mSend;

 

                            @Override

                            public void onCreate(Bundle icicle) {

                                          super.onCreate(icicle);

                                          setContentView(R.layout.main);

                                          myIGTalkSession = null;

                                          messageText = (EditText) findViewById(R.id.messageText);

                                          messageList = (ListView) findViewById(R.id.messageList);

                                          messageTo = (EditText) findViewById(R.id.messageTo);

                                          mSend = (Button) findViewById(R.id.btnSend);

                                          mSend.setOnClickListener(this);

                                          messageList.setBackgroundColor(Color.GRAY );

 

                                          this.bindService(new

                                                        Intent().setComponent(GTalkServiceConstants.GTALK_SERVICE_COMPONENT),

                                                        connection, 0);

                            }

 

                            private ServiceConnection connection = new ServiceConnection() {

                                          public void onServiceConnected(ComponentName name, IBinder service) {

                                                        try {

                                                                      myIGTalkSession =

                                                                      IGTalkService.Stub.asInterface(service).getDefaultSession();

                                                        } catch (DeadObjectException e) {

                                                                      myIGTalkSession = null;

                                                        }

                                          }

                           

                                          public void onServiceDisconnected(ComponentName name) {

                                                        myIGTalkSession = null;

                                          }

                            };

                           

                           

                            public void onClick(View view) {

                                          Cursor cursor = managedQuery(Im.Messages.CONTENT_URI, null,

                                                                                    "contact=\'" + messageTo.getText().toString() + "\'",

                                                                                    null, null);

 

                                          ListAdapter adapter = new SimpleCursorAdapter(this,

                                                                      android.R.layout.simple_list_item_1, cursor,

                                                                      new String[]{Im.MessagesColumns.BODY},

                                                                      new int[]{android.R.id.text1});

 

                                          this.messageList.setAdapter(adapter);

 

                                          try {

                                                        IChatSession chatSession;

                                                        chatSession =

                                                                      myIGTalkSession.createChatSession(messageTo.getText().toString());

                           

                                                        chatSession.sendTextMessage(messageText.getText().toString());

                           

                                          } catch (DeadObjectException ex) {

                                                        myIGTalkSession = null;

                                          }

                            }

              }

 

0 件のコメント:

コメントを投稿