嘿我是一个新的Android程序员,对于我正在开发的应用程序,我希望它是一个简单的聊天/消息应用程序。我在网上寻找教程,但没有看到任何。如果你们知道任何地方我可以参考或模板,将非常感激。感谢。
答案 0 :(得分:1)
可能是这段代码可以帮助你..我正在给你的代码,这作为谷歌谈话这个代码只适用于gmail id's ....还有一个更重要的事情你必须下载smack.jar < / strong>并将此jar文件导入libs文件夹.....
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 = "your gmail id";
public static final String PASSWORD = "your gmail id password";
在用户名中你必须输入你的Gmail密码...在密码的地方你必须输入你的Gmail密码.....关注代码,如果你想要任何澄清请通知我....
<强> MainActivity.java 强>
package com.example.androidwithoutxmppdialog;
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;
import android.widget.Toast;
public class MainActivity 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 = "your gmail id";
public static final String PASSWORD = "your gmail id 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.activity_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)&& (!textMessage.getText().toString().equals(""))) {
connection.sendPacket(msg);
//messages.add(connection.getUser() + ":");
messages.add("Rajesh :");
messages.add(text);
textMessage.setText("");
setListAdapter();
}
else
{
Toast.makeText(MainActivity.this, "please type to compose ", Toast.LENGTH_SHORT).show();
}
}
});
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());
String fromName="Gaurav";
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);
listview.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();
}
}
<强> activity_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
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="wrap_content"
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>
<强> 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" />
<强>的AndroidManifest.xml 强>
<uses-permission android:name="android.permission.INTERNET" />
答案 1 :(得分:1)
支持蓝牙聊天
package com.example.bluetoothchat;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View.OnClickListener;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity {
private static int DISCOVERY_REQUEST = 1;
private Handler handler = new Handler();
private ArrayList<BluetoothDevice> foundDevices;
private ArrayAdapter<BluetoothDevice> aa;
private ListView list;
private BluetoothAdapter bluetooth;
private BluetoothSocket socket;
private UUID uuid = UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666");
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
foundDevices=new ArrayList<BluetoothDevice>();
bluetooth = BluetoothAdapter.getDefaultAdapter();
searchPairedDevice();
listenPairedDevice();
displayDeviceLists();
forExit();
}
//----------------------------------------------------------------------------------------------------
private void displayDeviceLists() {
aa = new ArrayAdapter<BluetoothDevice>(this,android.R.layout.simple_list_item_1, foundDevices);
list = (ListView)findViewById(R.id.list_discovered);
list.setAdapter(aa);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, int index, long arg3) {
AsyncTask<Integer, Void, Void> connectTask = new AsyncTask<Integer, Void, Void>() {
@Override
protected Void doInBackground(Integer... params) {
try {
BluetoothDevice device = foundDevices.get(params[0]);
socket = device.createRfcommSocketToServiceRecord(uuid);
socket.connect();
} catch (IOException e)
{ Log.d("BLUETOOTH_CLIENT", e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(Void result) {
changeLayout();
}
};
connectTask.execute(index);
}
});
}
//-------------------------------------------------------------------------------------------------------
private void searchPairedDevice() {
Button searchBtn = (Button)findViewById(R.id.button_search);
searchBtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
registerReceiver(discoveryResult, new IntentFilter(BluetoothDevice.ACTION_FOUND));
if (!bluetooth.isDiscovering()) {
foundDevices.clear();
bluetooth.startDiscovery();
}
}
});
}
BroadcastReceiver discoveryResult = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device the if statement added later by MR.
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//added later by MR
bluetooth.cancelDiscovery();
BluetoothDevice remoteDevice;
remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (bluetooth.getBondedDevices().contains(remoteDevice)) {
foundDevices.add(remoteDevice);
aa.notifyDataSetChanged();
//added later by MR
clearAbortBroadcast ();
}
}
}
};
//-------------------------------------------------------------------------------------------------------
private void listenPairedDevice() {
Button listenBtn = (Button)findViewById(R.id.button_listen);
listenBtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Intent disc = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(disc, DISCOVERY_REQUEST);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == DISCOVERY_REQUEST) {
boolean isDiscoverable = resultCode > 0;
if (isDiscoverable) {
String name = "bluetoothserver";
try {
final BluetoothServerSocket btserver = bluetooth.listenUsingRfcommWithServiceRecord(name, uuid);
AsyncTask<Integer, Void, BluetoothSocket> acceptThread = new AsyncTask<Integer, Void, BluetoothSocket>() {
@Override
protected BluetoothSocket doInBackground(Integer... params) {
try {
socket = btserver.accept();
return socket;
} catch (IOException e) {
Log.d("BLUETOOTH", e.getMessage());
}
finally {
//close statement added later by MR
try{
btserver.close();
} catch (IOException e){
}
}
return null;
}
@Override
protected void onPostExecute(BluetoothSocket result) {
if (result != null)
changeLayout();
}
};
acceptThread.execute(resultCode);
} catch (IOException e) {
Log.d("BLUETOOTH", e.getMessage());
}
}
}
//------------------------------------------------------------------------------------------------------
}
private void changeLayout() {
final TextView messageText = (TextView)findViewById(R.id.text_messages);
final EditText textEntry = (EditText)findViewById(R.id.text_message);
messageText.setEnabled(true);
messageText.setVisibility(View.VISIBLE);
list.setVisibility(View.GONE);
textEntry.setEnabled(true);
textEntry.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
if ((keyEvent.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
sendMessage(socket, textEntry.getText().toString());
textEntry.setText("");
return true;
}
return false;
}
});
BluetoothSocketListener bsl = new BluetoothSocketListener(socket, handler, messageText);
Thread messageListener = new Thread(bsl);
messageListener.start();
}
//----------------------------------------------------------------------------------------------------
private void sendMessage(BluetoothSocket socket, String msg) {
OutputStream outStream;
try {
outStream = socket.getOutputStream();
byte[] byteString = (msg + " ").getBytes();
byteString[byteString.length - 1] = 0;
outStream.write(byteString);
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
//----------------------------------------------------------------------------------------------------
private class MessagePoster implements Runnable {
private TextView textView;
private String message;
public MessagePoster(TextView textView, String message) {
this.textView = textView;
this.message = message;
}
public void run() {
textView.setText(message);
}
}
//-------------------------------------------------------------------------------
private class BluetoothSocketListener implements Runnable {
private BluetoothSocket socket;
private TextView textView;
private Handler handler;
public BluetoothSocketListener(BluetoothSocket socket,
Handler handler, TextView textView) {
this.socket = socket;
this.textView = textView;
this.handler = handler;
}
public void run() {
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
try {
InputStream instream = socket.getInputStream();
int bytesRead = -1;
String message = "";
while (true) {
message = "";
bytesRead = instream.read(buffer);
if (bytesRead != -1) {
while ((bytesRead==bufferSize)&&(buffer[bufferSize-1] != 0)) {
message = message + new String(buffer, 0, bytesRead);
bytesRead = instream.read(buffer);
}
message = message + new String(buffer, 0, bytesRead - 1);
handler.post(new MessagePoster(textView, message));
socket.getInputStream();
}
}
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
}
//-----------------------------------------------------------------------------------------------------
private void forExit() {
Button stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
onDestroy();
}
});
}
public void onDestroy(){
super.onDestroy();
try{
if (socket!=null) {
socket.close();
}
} catch (IOException e){
}
finish();
}
}
main.xml中
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
<EditText android:id="@+id/text_message" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:enabled="false" />
<Button android:id="@+id/button_search" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_above="@id/text_message" android:text="SearchDevice" />
<Button android:id="@+id/button_listen" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_above="@id/button_search" android:text="ListenToDevice" />
<ListView android:id="@+id/list_discovered" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_above="@id/button_listen" android:layout_alignParentTop="true" />
<TextView android:id="@+id/text_messages" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_above="@id/button_listen" android:layout_alignParentTop="true" android:visibility="gone" />
<Button android:id="@+id/stop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:text="stop" />
</RelativeLayout>
的manifest.xml
<?xml version="1.0" encoding="utf-8" ?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.bluetoothchat" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
- <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme">
- <activity android:name="com.example.bluetoothchat.MainActivity" 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>