I am trying to make an android chat application. I am thinking about making it with aws. But the problem is that I am unable to find any good tutorial for doing this and I have no idea how to do it.
So could anyone please suggest some tutorial for sending push notification or on how to make a chat application?
Firebase is well suited to this due to its "realtime database" feature. Here's a few tutorials I found by Googling
https://code.tutsplus.com/tutorials/how-to-create-an-android-chat-app-using-firebase--cms-27397
http://myapptemplates.com/simple-android-chat-app-tutorial-firebase-integration/
https://codelabs.developers.google.com/codelabs/firebase-android/#0
Check Socket.IO for android. ( https://github.com/socketio/socket.io-client-java )
Its really easy to write a chat application. But you need a server side.
Easy to write a simple server for this chat app.
Server reveice the all message from clients and broadcast the message, to all.
Gradle:
compile 'com.github.nkzawa:socket.io-client:0.5.1'
Android manifest:
<uses-permission android:name="android.permission.INTERNET" />
Java
public static Socket mSocket;
try {
mSocket = IO.socket("http://192.168.1.104:4444");
mSocket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
Send messsage to server:
MainActivity.mSocket.emit("message","Text here...");
Create a listener for another message:
MainActivity.mSocket.on("newMessage", onMessageArrive); // Oncreate
private Emitter.Listener onMessageArrive = new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
String data = (String)args[0];
// Here is all message. add it to list :) Or Push notif
}
});
}
};
// Server side:
var http = require('http');
var express = require('express'),
app = module.exports.app = express();
var io = require('socket.io').listen(app.listen(4444));
io.on('connection', function (socket) {
socket.on("message",function(msg){
io.sockets.emit('newMessage', msg);
});
});
Run:
npm install express
npm install socket.io
node filename.js
Just dont forget to check you IP! :)
Done! You have a Real Time Chat!!
Related
My requirement is to do a SIP registration using java servlet and then make an audio call. In android i have found simple way to do Android Supporting SIP however i am not able use same android code in java since SIP manager class is present in android.net packages. What should i use for my users to do SIP registration in java servlet.
below is android code
if (sipManager == null) {
sipManager = SipManager.newInstance(this);
}
SipProfile.Builder builder = null;
try {
builder = new SipProfile.Builder("7001", "XXX.XXX.X.XXX");
builder.setPassword("XXX");
sipProfile = builder.build();
Intent i = new Intent();
i.setAction("android.SipDemo.INCOMING_CALL");
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, Intent.FILL_IN_DATA);
sipManager.open(sipProfile, pi, null);
sipManager.setRegistrationListener(sipProfile.getUriString(), new SipRegistrationListener() {
public void onRegistering(String localProfileUri) {
}
public void onRegistrationDone(String localProfileUri, long expiryTime) {
}
public void onRegistrationFailed(String localProfileUri, int errorCode,
String errorMessage) {
}
});
} catch (ParseException pe) {
pe.printStackTrace();
} catch (SipException se) {
se.printStackTrace();
}
It is not clear from your question how do you envisage this to work. Servlets are server side, so if SIP messages are initiated from the server but I suspect what you really want is to initiate a SIP session, followed by an Audio stream established with some real-time streaming protocol from the client.
There are Java APIs for SIP, and Sun / Oracle had a standard API for integrating with telecoms networks using SIP and IMS: https://www.oracle.com/technetwork/java/introduction-jain-sip-090386.html
Not sure if they are still maintained.
However, I suspect that this is not what you really need. Maybe you should look at this client based WebRTC and SIP client:
http://www.doubango.org/sipml5/
Your JSP would serve this Javascript, which allows the user to initiate a SIP session and establish the Audio call.
From their documentation, it seems to be straightforward:
SIPml.init(
function(e){
var stack = new SIPml.Stack({realm: 'example.org', impi: 'bob', impu: 'sip:bob#example.org', password: 'mysecret',
events_listener: { events: 'started', listener: function(e){
var callSession = stack.newSession('call-audiovideo', {
video_local: document.getElementById('video-local'),
video_remote: document.getElementById('video-remote'),
audio_remote: document.getElementById('audio-remote')
});
callSession.call('alice');
}
}
});
stack.start();
}
);
I'm totally desperate trying to do this. I Started a new job where I was given an app made in Processing and now I need it to call a simple index.html(https://west-4f2bc.firebaseapp.com) but not opening it on the browser.
Is there anyway to do it?
later I'm going to pass data adding parameters in URL but now I just need to call it as it is without a window opening.
Please Help me.....
I tried a lot of variants of this code
import processing.net.*;
Client myClient;
void setup() {
// Connect to the local machine at port 10002.
// This example will not run if you haven't
// previously started a server on this port.
myClient = new Client(this, "west-4f2bc.firebaseapp.com", 80);
// Say hello
myClient.write("GET /\r\n");
}
void draw() {
}
Thanks.
With this I only get true, so it connects but I only get 0.
import processing.net.*;
Client myClient;
int dataIn;
void setup() {
size(200, 200);
// Connect to the local machine at port 5204.
// This example will not run if you haven't
// previously started a server on this port.
myClient = new Client(this, "west-4f2bc.firebaseapp.com", 80);
println(myClient.active());
println(dataIn);
}
void draw() {
}
with this I get connected but after Client SocketException: Socket closed
import processing.net.*;
Client myClient;
int dataIn;
void setup() {
Client client;
client = new Client(this, "west-4f2bc.firebaseapp.com", 80);
if (client.active()==true) {
println("connected");
// Make a HTTP request:
client.write("GET /call.html?id=ola&nome=artur\r\n");
client.write("\r\n");
client.stop();
} else {
// if you didn't get a connection to the server:
println("connection failed");
}
}
I've never really used Processing's Networking library, but from what I can tell it's not usually used to read data from a website- it's used for lower-level communication between a client and server. It might be possible to use it to read a website, but what you have already looks more complicated than it has to be.
Remember that Processing is built on top of Java, so anything you can do in Java, you can do in Processing. If I were you, I would do a google search for "java read website" for a ton of results, including:
Reading Directly from a URL
How to read a text file directly from Internet using Java?
Reading website's contents into string
How to read a text from a web page with Java?
Using Java to pull data from a webpage?
I used another library.
import http.requests.*;
void setup()
{
size (100, 100);
}
void draw()
{
PostRequest post = new PostRequest("https://"+"www.example.com");
post.send();
System.out.println("Reponse Content: " + post.getContent());
System.out.println("Reponse Content-Length Header: " + post.getHeader("Content-Length"));
noLoop();
}
Still doesnt does my final objective but at least it can communicate with the page.
I'm using the jmdns.jar from this project https://github.com/twitwi/AndroidDnssdDemo in my Android project.
I'm currently trying to find all services on my network. I can't use Android NSD, so please avoid suggesting it as a solution.
protected Object doInBackground(Object[] params) {
try {
WifiManager wifi = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
final InetAddress deviceIpAddress = InetAddress.getByName(Formatter.formatIpAddress(wifi.getConnectionInfo().getIpAddress()));
multicastLock = wifi.createMulticastLock(getClass().getName());
multicastLock.setReferenceCounted(true);
multicastLock.acquire();
jmDNS = JmDNS.create(deviceIpAddress, "Android Device Discovery");
jmDNS.addServiceListener("_http._tcp.local.", new ServiceListener() {//_services._dns-sd._udp _http._tcp.local. _workstation._tcp.local.
#Override
public void serviceAdded(ServiceEvent serviceEvent) {
jmDNS.requestServiceInfo("", "", 1000);
}
#Override
public void serviceRemoved(ServiceEvent serviceEvent) {
}
#Override
public void serviceResolved(ServiceEvent serviceEvent) {
System.out.println(serviceEvent.getInfo().getHostAddress());
System.out.println(serviceEvent.getInfo().getName());
}
});
}catch(IOException e) {
Log.e(TAG, e.getMessage(), e);
}
}
The above code gives me the address and name of a printer on my network. That's great. What I would like is a TYPE that will catch all the services being broadcasted on my network. Android NSD had a _services._dns-sd._udpthat could be used for the type of service and find all services on the network. This doesn't work with jmDNS. I can't find anything in the limited documentation about this.
Do I need to go through and add all the service types myself? That is not a very clean solution.
I have the proper perms in my AndroidManifest.
Try adding the dot at the end, my jmdns app crashed without it..
Also try adding the .local. by yourself with the service type.
I'm trying to send the content of a DataMap from an Android device to a wearable. It works fine when the app is in the foreground on my app but once I lock the mobile device it gets stuck at the pendingResult.await() and the wearable doesn't receive any data where as it normal would if I keep the app open.
public void send(final DataMap dataMap) {
new Thread(new Runnable() {
#Override
public void run() {
PutDataMapRequest putDMR = PutDataMapRequest.create(WEARABLE_DATA_PATH);
putDMR.getDataMap().putAll(dataMap);
PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi.putDataItem(googleClient, request);
DataApi.DataItemResult result = pendingResult.await();
if(result.getStatus().isSuccess()) {
Log.d("qwe", "Data item set: " + result.getDataItem().getUri());
}
}
}).start();
}
This method is in a class which extends WearableListenerService and I have added the XML in the AndroidMainfest for the service also. Am I doing something completely wrong or missing something?
Thanks
try to check google api client status for each send.
use blockingConnect when google api client is not connected.
Found out I was doing googleClient.disconnect() in my main activity onStop() which was causing it to hang as googleClient wasn't connected once my app was in the background.
I am new to android. I am developing the new app with email sending option. To send a mail I have used gmail configurations host "smtp.gmail.com", port 465 with SSL true. To send an email I have apache commons API. OnTouch event mail sending method will call. Whenever touch button it shows following errors,
Error : Could not find class 'javax.naming.InitialContext', referenced from method org.apache.commons.mail.Email.setMailSessionFromJNDI
Warning: VFY: unable to resolve new-instance 955 (Ljavax/naming/InitialContext;) in Lorg/apache/commons/mail/Email;
Warning : org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.gmail.com:465
I have added uses-permission android:name="android.permission.INTERNET" in my manifest file.
Can i use all java files in android ?
My email code executed correctly as a stand alone java program.
Here is an example of what I am doing in an app. I have an app that has its own email account that sends an email to the user when they fill out a form and press the submit button.
Important make sure you have the libSMTP.jar file referenced in your app. I am using this library for the following code. Here is the following code being used, take from it what you'd like, hope this is useful:
Imports needed:
import org.apache.commons.net.smtp.SMTPClient;
import org.apache.commons.net.smtp.SMTPReply;
import org.apache.commons.net.smtp.SimpleSMTPHeader;
Submit button to make the request to send email
submit.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
//-- Submit saves data to sqlite db, but removed that portion for this demo...
//-- Executes an new task to send an automated email to user when they fill out a form...
new sendEmailTask().execute();
}
}
});
Email task to be preformed on seperate thread:
private class sendEmailTask extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPostExecute(Void result)
{
}
#Override
protected void onPreExecute()
{
}
#SuppressLint("ParserError")
#Override
protected Void doInBackground(Void... params)
{
try {
//--Note the send format is as follows: send(from, to, subject line, body message)
send("myAppName#gmail.com", "emailToSendTo#gmail.com", "Form Submitted", "You submitted the form.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Send function being used:
public void send(String from, String to, String subject, String text) throws IOException
{
SMTPClient client = new SMTPClient("UTF-8");
client.setDefaultTimeout(60 * 1000);
client.setRequireStartTLS(true); // requires STARTTLS
//client.setUseStartTLS(true); // tries STARTTLS, but falls back if not supported
client.setUseAuth(true); // use SMTP AUTH
//client.setAuthMechanisms(authMechanisms); // sets AUTH mechanisms e.g. LOGIN
client.connect("smtp.gmail.com", 587);
checkReply(client);
//--Note the following format is as follows: client.login("localhost", (...your email account being used to send email from...), (...your email accounts password ...));
client.login("localhost", "myAppName#gmail.com", "...myAppName email account password...");
checkReply(client);
client.setSender(from);
checkReply(client);
client.addRecipient(to);
checkReply(client);
Writer writer = client.sendMessageData();
if (writer != null)
{
SimpleSMTPHeader header = new SimpleSMTPHeader(from, to, subject);
writer.write(header.toString());
writer.write(text);
writer.close();
client.completePendingCommand();
checkReply(client);
}
client.logout();
client.disconnect();
}
Check reply function being used:
private void checkReply(SMTPClient sc) throws IOException
{
if (SMTPReply.isNegativeTransient(sc.getReplyCode()))
{
sc.disconnect();
throw new IOException("Transient SMTP error " + sc.getReplyCode());
}
else if (SMTPReply.isNegativePermanent(sc.getReplyCode()))
{
sc.disconnect();
throw new IOException("Permanent SMTP error " + sc.getReplyCode());
}
}
From Apache Commons Net 3.3, you can just drop the jar in your classpath and start using the AuthenticationSMTPClient : http://blog.dahanne.net/2013/06/17/sending-a-mail-in-java-and-android-with-apache-commons-net/