When i rum my application it will give me error
MainActivity
public class MainActivity<XMPPConnection> 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;
public static String setConnection;
/**
* Called with the activity is first created.
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Log.i("XMPPClient", "onCreate called");
setContentView(R.layout.activity_main);
mRecipient = (EditText) this.findViewById(R.id.recipient);
Log.i("XMPPClient", "mRecipient = " + mRecipient);
mSendText = (EditText) this.findViewById(R.id.sendText);
Log.i("XMPPClient", "mSendText = " + mSendText);
mList = (ListView) this.findViewById(R.id.listMessages);
Log.i("XMPPClient", "mList = " + mList);
setListAdapter();
// Dialog for getting the xmpp settings
mDialog = new SettingsDialog(this);
new MyTask().execute();
// 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) {
new MyTask().execute();
}
});
// 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);
((org.jivesoftware.smack.XMPPConnection) connection).sendPacket(msg);
messages.add(((org.jivesoftware.smack.XMPPConnection) 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) 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,
R.layout.multi_line_list_item,
messages);
mList.setAdapter(adapter);
}
}
Here is my MyTask class
private MainActivity<XMPPConnection> MainActivity;
private XMPPConnection setConnection;
#Override
protected String doInBackground(String... params) {
String host = "web.vlivetech.com"; //getText(R.id.host);
String port = "5222"; //
String service = "web.vlivetech.com";// getText(R.id.service);
String username ="has12345"; // getText(R.id.userid); //
String password = "123";// getText(R.id.password); //
// Create a connection
ConnectionConfiguration connConfig =
new ConnectionConfiguration(host, Integer.parseInt(port), service);
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());
MainActivity.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);
**MainActivity.setConnection(connection);**
} catch (XMPPException ex) {
Log.e("XMPPClient", "[SettingsDialog] Failed to log in as " + username);
MainActivity.setConnection(null);
}
return null;
}
private String getText(int id) {
EditText widget = (EditText) this.findViewById(id);
return widget.getText().toString();
}
private EditText findViewById(int id) {
// TODO Auto-generated method stub
return null;
}
}
when i debug my code this will get the connection values but terminate on this line MainActivity.setConnection(connection);
now what i am doing wrong
getText(int host)
is returning null for host, port, service, username and password. That will not bring you very far.
Related
Trying this...
public class MainActivity extends Activity {
PendingIntent mPermissionIntent;
Button btnCheck;
TextView textInfo;
UsbDevice device;
UsbManager manager;
private static final String ACTION_USB_PERMISSION = "com.mobilemerit.usbhost.USB_PERMISSION";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCheck = (Button) findViewById(R.id.check);
textInfo = (TextView) findViewById(R.id.info);
btnCheck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
textInfo.setText("");
checkInfo();
}
});
}
public void startPrinting(final UsbDevice printerDevice) {
new Handler().post(new Runnable() {
UsbDeviceConnection conn;
UsbInterface usbInterface;
#Override
public void run() {
try {
Log.e("Info", "Bulk transfer started");
usbInterface = printerDevice.getInterface(0);
UsbEndpoint endPoint = usbInterface.getEndpoint(0);
conn = manager.openDevice(device);
conn.claimInterface(usbInterface, true);
String myStringData = "\nThis \nis \nmy \nsample \ntext";
byte[] array = myStringData.getBytes();
ByteBuffer output_buffer = ByteBuffer
.allocate(array.length);
UsbRequest request = new UsbRequest();
request.initialize(conn, endPoint);
request.queue(output_buffer, array.length);
if (conn.requestWait() == request) {
Log.i("Info", output_buffer.getChar(0) + "");
Message m = new Message();
m.obj = output_buffer.array();
// handler.sendMessage(m);
output_buffer.clear();
} else {
Log.e("Info", "No request recieved");
}
// int transfered = conn.bulkTransfer(endPoint,
// myStringData.getBytes(),
// myStringData.getBytes().length, 5000);
// Log.i("Info", "Amount of data transferred : " +
// transfered);
} catch (Exception e) {
Log.e("Exception", "Unable to transfer bulk data");
e.printStackTrace();
} finally {
try {
conn.releaseInterface(usbInterface);
Log.e("Info", "Interface released");
conn.close();
Log.e("Info", "Usb connection closed");
unregisterReceiver(mUsbReceiver);
Log.e("Info", "Brodcast reciever unregistered");
} catch (Exception e) {
Log.e("Exception",
"Unable to release resources because : "
+ e.getMessage());
e.printStackTrace();
}
}
}
});
}
private void checkInfo() {
manager = (UsbManager) getSystemService(Context.USB_SERVICE);
/*
* this block required if you need to communicate to USB devices it's
* take permission to device
* if you want than you can set this to which device you want to communicate
*/
// ------------------------------------------------------------------
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
// -------------------------------------------------------------------
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
String i = "";
while (deviceIterator.hasNext()) {
device = deviceIterator.next();
manager.requestPermission(device, mPermissionIntent);
i += "\n" + "DeviceID: " + device.getDeviceId() + "\n"
+ "DeviceName: " + device.getDeviceName() + "\n"
+ "DeviceClass: " + device.getDeviceClass() + " - "
+ "DeviceSubClass: " + device.getDeviceSubclass() + "\n"
+ "VendorID: " + device.getVendorId() + "\n"
+ "ProductID: " + device.getProductId() + "\n";
}
textInfo.setText(i);
if(!(i.equalsIgnoreCase("")))
{
startPrinting(device);
}
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
// call method to set up device communication
}
} else {
Log.d("ERROR", "permission denied for device " + device);
}
}
}
}
};
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mUsbReceiver);
}
}
This code shows the device connected with OTG but Not Accepted as printer device to canon 2900b
Printer going in idle mode.
or phone got hanged
I'm having some troubles while trying to visualize the message send from the TCP Server as response to my TCP Client
Here is my Client.java code
public class Client {
public static String SERVER_IP; //server IP address
public static String ipp;
public static final int SERVER_PORT = 4444;
// message to send to the server
private String mServerMessage;
// sends message received notifications
private OnMessageReceived mMessageListener = null;
// while this is true, the server will continue running
private boolean mRun = false;
// used to send messages
private PrintWriter mBufferOut;
// used to read messages from the server
private BufferedReader mBufferIn;
/**
* Constructor of the class. OnMessagedReceived listens for the messages received from server
*/
public Client(OnMessageReceived listener) {
mMessageListener = listener;
}
/**
* Sends the message entered by client to the server
*
* #param message text entered by client
*/
public void sendMessage(String message) {
if (mBufferOut != null && !mBufferOut.checkError()) {
mBufferOut.println(message);
mBufferOut.flush();
}
}
/**
* Close the connection and release the members
*/
public void stopClient() {
mRun = false;
if (mBufferOut != null) {
mBufferOut.flush();
mBufferOut.close();
}
mMessageListener = null;
mBufferIn = null;
mBufferOut = null;
mServerMessage = null;
}
public void run() {
mRun = true;
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
Log.e("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, SERVER_PORT);
try {
//sends the message to the server
mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
//receives the message which the server sends back
mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//in this while the client listens for the messages sent by the server
while (mRun) {
mServerMessage = mBufferIn.readLine();
if (mServerMessage != null && mMessageListener != null) {
//call the method messageReceived from MyActivity class
mMessageListener.messageReceived(mServerMessage);
}
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + mServerMessage + "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
//the socket must be closed. It is not possible to reconnect to this socket
// after it is closed, which means a new socket instance has to be created.
socket.close();
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
//class at on asynckTask doInBackground
public interface OnMessageReceived {
public void messageReceived(String message);
}
}
While here is the MainActivity :
public class MainActivity extends AppCompatActivity {
Server server;
static Client client;
settings Settings;
public static TextView terminale, indr, msg;
TextView log;
static String ipp;
static String trm;
static DataBaseHandler myDB;
allert Allert;
SharedPreferences prefs;
String s1 = "GAB Tamagnini SRL © 2017 \n" +
"Via Beniamino Disraeli, 17,\n" +
"42124 Reggio Emilia \n" +
"Telefono: 0522 / 38 32 22 \n" +
"Fax: 0522 / 38 32 72 \n" +
"Partita IVA, Codice Fiscale \n" +
"Reg. Impr. di RE 00168780351 \n" +
"Cap. soc. € 50.000,00 i.v. \n" + "" +
"REA n. RE-107440 \n" +
"presso C.C.I.A.A. di Reggio Emilia";
ImageButton settings, helps, allerts, home;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Utils.darkenStatusBar(this, R.color.colorAccent);
server = new Server(this);
myDB = DataBaseHandler.getInstance(this);
msg = (TextView) findViewById(R.id.msg);
log = (TextView) findViewById(R.id.log_avviso);
settings = (ImageButton) findViewById(R.id.impo);
helps = (ImageButton) findViewById(R.id.aiut);
allerts = (ImageButton) findViewById(R.id.msge);
home = (ImageButton) findViewById(R.id.gab);
terminale = (TextView) findViewById(R.id.terminal);
indr = (TextView) findViewById(R.id.indr);
final Cursor cursor = myDB.fetchData();
if (cursor.moveToFirst()) {
do {
indr.setText(cursor.getString(1));
terminale.setText(cursor.getString(2));
Client.SERVER_IP = cursor.getString(1);
trm = cursor.getString(2);
} while (cursor.moveToNext());
}
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
ipp = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
startConnection.postDelayed(runnableConnection,5000);
startMessage.postDelayed(runnableMessage,5500);
cursor.close();
server.Parti();
home.setOnClickListener(new View.OnClickListener() {
int counter = 0;
#Override
public void onClick(View view) {
counter++;
if (counter == 10) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(true);
builder.setMessage(s1);
builder.show();
counter = 0;
}
}
});
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent impostazioni = new Intent(getApplicationContext(), settingsLogin.class);
startActivity(impostazioni);
}
});
helps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent pgHelp = new Intent(getApplicationContext(), help.class);
startActivity(pgHelp);
}
});
allerts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Server.count = 0;
SharedPreferences prefs = getSharedPreferences("MY_DATA", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.apply();
msg.setVisibility(View.INVISIBLE);
Intent pgAlert = new Intent(getApplicationContext(), allert.class);
startActivity(pgAlert);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
server.onDestroy();
}
public static class ConnectTask extends AsyncTask<String, String, Client> {
#Override
protected Client doInBackground(String... message) {
client = new Client(new Client.OnMessageReceived() {
#Override
public void messageReceived(String message) {
messageReceived(message);
}
});
client.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Log.d("test", "response " + values[0]);
}
}
static Handler startConnection = new Handler();
static Runnable runnableConnection = new Runnable() {
#Override
public void run() {
new ConnectTask().execute("");
}
};
static Handler startMessage = new Handler();
static Runnable runnableMessage = new Runnable() {
#Override
public void run() {
final Cursor cursor = myDB.fetchData();
if (cursor.moveToFirst()) {
do {
Client.SERVER_IP = cursor.getString(1);
trm = cursor.getString(2);
} while (cursor.moveToNext());
}
if (client != null) {
client.sendMessage(ipp + "#" + trm);
}
}
};
}
So what i'm trying to do is receive message from the server and visualize it in help.java activity in a TextView called msgServer set as static.
Actually i don't know which value i have to attribute to the help.msgServer.setText() and where to put it in MainActivity.
Fixed by setting in AsyncTask in MainActivity following code:
msgServer.setTextColor(Color.parseColor("#00FF00"));
msgServer.setText("ONLINE");
in the onProgressUpdate method.
So i identified the right place from where i can get the message sent by the server, the message is contained in:
values
.
I am trying to write an Android app that could communicate over WiFi with ESP8266 module and exchange some simple, basic text data. My problem is I can not get any communication to work. I am not sure if my problem is with the Android code or some bad network configuration on the ESP.
On the Android side, I am using a standard TCPclient class code from this thread to transmit data. In this app I can get WiFi to work and to connect with ESP module using SSID and password authorization.
This is how my app looks like.
Here is TCPclient.java class code I used.
package com.example.wexfo.wifi_com;
import ...
public class TCPclient {
private String serverMessage;
public static final String SERVER_IP = "192.168.0.102";
public static final int SERVER_PORT = 4444;
private OnMessageReceived messageListener = null;
private boolean run = false;
public static final String LOG_TAG = "TCP";
PrintWriter out;
BufferedReader in;
public TCPclient(OnMessageReceived listener) {
messageListener = listener;
}
public void sendMessage(String message) {
if (out != null && !out.checkError()) {
out.println(message);
out.flush();
}
}
public void stopClient() {
run = false;
if (out != null) {
out.flush();
out.close();
}
messageListener = null;
in = null;
out = null;
serverMessage = null;
}
public void run() {
run = true;
try {
InetAddress serverAddress = InetAddress.getByName(SERVER_IP);
Log.e(LOG_TAG, "C: Connecting...");
Socket socket = new Socket(serverAddress, SERVER_PORT);
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Log.e(LOG_TAG, "C: Sent.");
Log.e(LOG_TAG, "C: Done.");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (run) {
serverMessage = in.readLine();
if (serverMessage != null && messageListener != null) {
messageListener.messageReceived(serverMessage);
}
//serverMessage = null;
}
Log.e(LOG_TAG, "S: Received message: '" + serverMessage + "'.");
}
catch (Exception e) {
Log.e(LOG_TAG, "S: Error", e);
}
finally {
socket.close();
}
}
catch (Exception e) {
Log.e(LOG_TAG, "C: Error", e);
}
}
public interface OnMessageReceived {
void messageReceived(String message);
}
}
Below is MainActivity.java code.
package com.example.wexfo.wifi_com;
import ...
public class MainActivity extends AppCompatActivity {
// Labels and edits
private TextView connectionText;
private EditText messageText;
private TextView chatText;
// Buttons
private ToggleButton connectButton;
private Button sendButton;
// Wifi connection
private static final String NET_SSID = "AI-THINKER";
private static final String NET_PASSWD = "aiTHINKERwifi";
private WifiConfiguration wifiConfig;
private WifiManager wifiManager;
// Other
private TCPclient tcpClient;
private void printChatLine(String text) {
chatText.append("\n>> " + text);
}
private void printChatLine(String who, String text) {
chatText.append("\n" + who + ": " + text);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectionText = (TextView) findViewById(R.id.connectionText);
messageText = (EditText) findViewById(R.id.messageText);
chatText = (TextView) findViewById(R.id.chatText);
chatText.setMovementMethod(new ScrollingMovementMethod());
printChatLine("chat test");
// WiFi setup (authorization hard-coded for now)
wifiConfig = new WifiConfiguration();
wifiConfig.SSID = "\"" + NET_SSID + "\"";
wifiConfig.preSharedKey = "\"" + NET_PASSWD + "\"";
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(wifiConfig);
connectButton = (ToggleButton) findViewById(R.id.connectButton);
connectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (connectButton.isChecked()) {
connectionText.setText("Disconnect WiFi");
if (!wifiManager.isWifiEnabled())
wifiManager.setWifiEnabled(true);
List<WifiConfiguration> netList = wifiManager.getConfiguredNetworks();
for (WifiConfiguration net : netList) {
if (net.SSID != null && net.SSID.equals("\"" + NET_SSID + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(net.networkId, true);
wifiManager.reconnect();
break;
}
}
// Start server connection thread
new ConnectTask().execute("");
}
else {
connectionText.setText("Connect WiFi");
if (wifiManager.isWifiEnabled())
wifiManager.setWifiEnabled(false);
// Stop server connection thread
if (tcpClient != null)
tcpClient.stopClient();
}
}
});
sendButton = (Button) findViewById(R.id.sendButton);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String message = messageText.getText().toString();
printChatLine("ME", message);
messageText.setText("");
// Send message to ESP
if (tcpClient != null)
tcpClient.sendMessage(message);
}
});
}
public class ConnectTask extends AsyncTask<String,String,TCPclient> {
#Override
protected TCPclient doInBackground(String... message) {
tcpClient = new TCPclient(new TCPclient.OnMessageReceived() {
#Override
public void messageReceived(String message) {
publishProgress(message);
}
});
tcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
// Received message from ESP
printChatLine("ES", values[0]);
}
}
}
Now the ESP8266 is set to work as SoftAP
AT+CWMODE?
+CWMODE:3
OK
Then I make a basic setup for multiple connections and start a new server.
AT+CIPSTA="192.168.0.102"
OK
AT+CIPMUX=1
OK
AT+CIPSERVER=1,4444
OK
Here is my IP data.
AT+CIFSR
+CIFSR:APIP,"192.168.4.1"
+CIFSR:APMAC,"1a:fe:34:8e:81:58"
+CIFSR:STAIP,"192.168.0.102"
+CIFSR:STAMAC,"18:fe:34:8e:81:58"
OK
Now when I run my app I can confirm I am connected to ESP's access point.
AT+CWLIF
192.168.4.2,00:27:15:77:82:02
OK
However there is no sign of an opened connection on the ESP and clicking SEND button does not make any data transfer. When I try to connect through ESP, I get an ERROR.
AT+CIPSTART=0,"TCP","192.168.4.2",4444
0,CLOSED
ERROR
My feeling is the app works fine but I do something horribly wrong on the ESP side and I can not figure out what it is. Maybe I have a wrong idea about the entire setup?
I m trying to make a simple version facebook messenger.The code that i used has worked well for gtalk and requires facebook authentication to be used for chatting with facebook friends.For that, i have used SASLXFacebookPlatfromMechanism class where i will store the api token and api key along with the apisecret of my app. The problem is SASLXFacebookPlatfromMechanism.java class is full of errors which i cannot resolve at all.Here are my classes-
**MainActivity.java**
public class MainActivity extends ActionBarActivity {
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);
Log.i("XMPPClient", "onCreate called");
setContentView(R.layout.activity_main);
mRecipient = (EditText) this.findViewById(R.id.recipient);
Log.i("XMPPClient", "mRecipient = " + mRecipient);
mSendText = (EditText) this.findViewById(R.id.sendText);
Log.i("XMPPClient", "mSendText = " + mSendText);
mList = (ListView) this.findViewById(R.id.listMessages);
Log.i("XMPPClient", "mList = " + mList);
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) {
try
{
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();
}catch(Exception e)
{
Toast.makeText(MainActivity.this, "Error="+e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
/**
* 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,
R.layout.multi_line_list_item,
messages);
mList.setAdapter(adapter);
}
}
SettingsDialog.java
public class SettingsDialog extends Dialog implements android.view.View.OnClickListener {
private MainActivity xmppClient;
public SettingsDialog(MainActivity 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) {
final String host = "chat.facebook.com";
final String port = ""+5222;
final String service = "chat.facebook.com";
final String username = "*****";
final String password = "****";
new Thread() {
public void run() {
// Create a connection
ConnectionConfiguration connConfig =new ConnectionConfiguration(host, Integer.parseInt(port), service);
connConfig.setSASLAuthenticationEnabled(true);
XMPPConnection connection = new XMPPConnection(connConfig);
try {
connection.connect();
Log.i("XMPPClient", "[SettingsDialog] Connected to " + connection.getHost());
} catch (Exception ex) {
Log.e("XMPPClient", "[SettingsDialog] Failed to connect to " + connection.getHost());
Log.e("XMPPClient", ex.toString());
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);
Log.e("XMPPClient", ex.toString());
xmppClient.setConnection(null);
}
}
}.start();
dismiss();
}
private String getText(int id) {
EditText widget = (EditText) this.findViewById(id);
return widget.getText().toString();
}
}
SASLXFacebookPlatformMechanism.java
public class SASLXFacebookPlatformMechanism extends SASLMechanism
{
private static final String NAME = "X-FACEBOOK-PLATFORM";
private String apiKey = "";
private String applicationSecret = "";
private String sessionKey = "";
/**
* Constructor.
*/
public SASLXFacebookPlatformMechanism(SASLAuthentication saslAuthentication)
{
super(saslAuthentication);
}
#Override
protected void authenticate() throws IOException, XMPPException
{
getSASLAuthentication().send(new AuthMechanism(NAME, ""));
}
#Override
public void authenticate(String apiKeyAndSessionKey, String host,
String applicationSecret) throws IOException, XMPPException
{
if (apiKeyAndSessionKey == null || applicationSecret == null)
{
throw new IllegalArgumentException("Invalid parameters");
}
String[] keyArray = apiKeyAndSessionKey.split("\\|", 2);
if (keyArray.length < 2)
{
throw new IllegalArgumentException(
"API key or session key is not present");
}
this.apiKey = keyArray[0];
this.applicationSecret = applicationSecret;
this.sessionKey = keyArray[1];
this.authenticationId = sessionKey;
this.password = applicationSecret;
this.hostname = host;
String[] mechanisms = { "DIGEST-MD5" };
Map<String, String> props = new HashMap<String, String>();
this.sc =
Sasl.createSaslClient(mechanisms, null, "xmpp", host, props,
this);
authenticate();
}
#Override
public void authenticate(String username, String host, CallbackHandler cbh)
throws IOException, XMPPException
{
String[] mechanisms = { "DIGEST-MD5" };
Map<String, String> props = new HashMap<String, String>();
this.sc =
Sasl.createSaslClient(mechanisms, null, "xmpp", host, props,
cbh);
authenticate();
}
#Override
protected String getName()
{
return NAME;
}
#Override
public void challengeReceived(String challenge) throws IOException
{
byte[] response = null;
if (challenge != null)
{
String decodedChallenge = new String(Base64.decode(challenge));
Map<String, String> parameters = getQueryMap(decodedChallenge);
String version = "1.0";
String nonce = parameters.get("nonce");
String method = parameters.get("method");
long callId = new GregorianCalendar().getTimeInMillis();
String sig =
"api_key=" + apiKey + "call_id=" + callId + "method="
+ method + "nonce=" + nonce + "session_key="
+ sessionKey + "v=" + version + applicationSecret;
try
{
sig = md5(sig);
} catch (NoSuchAlgorithmException e)
{
throw new IllegalStateException(e);
}
String composedResponse =
"api_key=" + URLEncoder.encode(apiKey, "utf-8")
+ "&call_id=" + callId + "&method="
+ URLEncoder.encode(method, "utf-8") + "&nonce="
+ URLEncoder.encode(nonce, "utf-8")
+ "&session_key="
+ URLEncoder.encode(sessionKey, "utf-8") + "&v="
+ URLEncoder.encode(version, "utf-8") + "&sig="
+ URLEncoder.encode(sig, "utf-8");
response = composedResponse.getBytes("utf-8");
}
String authenticationText = "";
if (response != null)
{
authenticationText =
Base64.encodeBytes(response, Base64.DONT_BREAK_LINES);
}
// Send the authentication to the server
getSASLAuthentication().send(new Response(authenticationText));
}
private Map<String, String> getQueryMap(String query)
{
Map<String, String> map = new HashMap<String, String>();
String[] params = query.split("\\&");
for (String param : params)
{
String[] fields = param.split("=", 2);
map.put(fields[0], (fields.length > 1 ? fields[1] : null));
}
return map;
}
private String md5(String text) throws NoSuchAlgorithmException,
UnsupportedEncodingException
{
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(text.getBytes("utf-8"), 0, text.length());
return convertToHex(md.digest());
}
private String convertToHex(byte[] data)
{
StringBuilder buf = new StringBuilder();
int len = data.length;
for (int i = 0; i < len; i++)
{
int halfByte = (data[i] >>> 4) & 0xF;
int twoHalfs = 0;
do
{
if (0 <= halfByte && halfByte <= 9)
{
buf.append((char) ('0' + halfByte));
}
else
{
buf.append((char) ('a' + halfByte - 10));
}
halfByte = data[i] & 0xF;
} while (twoHalfs++ < 1);
}
return buf.toString();
}
#Override
protected String getAuthenticationText(String arg0, String arg1, String arg2) {
// TODO Auto-generated method stub
return null;
}
#Override
protected String getChallengeResponse(byte[] arg0) {
// TODO Auto-generated method stub
return null;
}
}
The code shows error stating
"The method send(String) in the type SASLAuthentication is not applicable for arguments(Response).The constructor Response(String) is undefined"
in the line-->"getSASLAuthentication().send(new Response(authenticationText));"
I am also confused on how to use this SASLXFacebookPlatformMechanism.java class in my MainActivity.class.I have been trying to get a sense of how it works but failing.A complete guideline on how to develop a xmpp facebook chat client using asmack library would be appreciated since the internet lacks enough documentation on it.Thanks.
[I have the apikeys and apitokens,so the empty string will not remain empty]
Hi I'm starting android development and trying to do an instant messaging/chat app.
I downloaded this source code here and trying to understand how it works. My problem is on 2 mobile devices, 1 user cannot receive the message of the other user, and vice versa, but I can see those chat message on gmail accounts. And if i type a message from gmail account browser the user who use the mobile device received the message(which made me think the problem is in "connection.sendPacket(msg);").
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 = "xxxxxxxx#gmail.com";
public static final String PASSWORD = "xxxxxxx";
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();
Message msg = new Message(to, Message.Type.groupchat);
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
*
* #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() {
#Override
public void processPacket(Packet packet) {
Message message = (Message) packet;
if (message.getBody() != null) {
String fromName = StringUtils.parseBareAddress(message.getFrom());
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 {
if (connection != null)
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",
"Connected to " + connection.getHost());
} catch (XMPPException ex) {
Log.e("XMPPChatDemoActivity", "Failed to connect to "
+ connection.getHost());
Log.e("XMPPChatDemoActivity", ex.toString());
setConnection(null);
}
try {
// SASLAuthentication.supportSASLMechanism("PLAIN", 0);
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();
}
}
Thank you very much.