Discovering all services on the network using jmDNS on Android - java

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.

Related

How to make multiple okhttp3 requests at the same time Android Studio

Good Afternoon, I am still very new to ESP32/android studio coding so I apologize for my beginner terminology. I am currently coding a project where I can control multiple stepper motors at the same exact time from the press of a button on my android application and the motors are connected to certain ESP32 GPIO pins, I am using the okhttp3 client as well. My code is below.
public class Connectivity {
public static String geturl (String url_esp32){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url_esp32)
.build();
try
{
Response response = client.newCall(request).execute();
return response.body().string();
} catch(IOException error) {
return error.toString();
}
}
}
above is my connectivity page for connecting to the requests for the esp32.
PBNow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// request information from esp32
// PB sandwich now, disable jelly motor
request_to_url("STEP");
request_to_url("DIR");
request_to_url("STEP2");
request_to_url("DIR2");
request_to_url("STEP4");
request_to_url("DIR4");
request_to_url("ledRED");
request_to_url("ledGREEN");
}
});
above is how im calling the requests for the esp32.
The problem I am having is that when these request_to_url lines are going line by line but I want them to all run at the exact same time. Is this possible.
Below are also my request_to_url function and request_data function.
public void request_to_url (String command) {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnected()) {
new request_data().execute("http://" + ip_address + "/" + command);
}else {
Toast.makeText(activity_2.this, "Not connected ", Toast.LENGTH_LONG).show();
}
}
private class request_data extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... url)
{
return Connectivity.geturl(url[0]);
}
#Override
protected void onPostExecute(String result_data) {
if(result_data != null)
{
}else{
Toast.makeText(activity_2.this, "Null data", Toast.LENGTH_LONG).show();
}
}
}
I apologize if the code is very sloppy, I am still very new. Thank you very much.
Besides the messy code in your app required to fire off multiple requests, the ESP32 has very limited network stack and resources, and cannot handle many simultaneous connections. If your app opens too many HTTP connections to the ESP32 at once, some will likely fail or have to wait for others to close.
Instead, you can do it all in a single request and tell the ESP32 to do multiple things at once. Pass the requests as parameters in the URL, like so:
http://ip-address/cmd?step=1&dir=0&ledGREEN=0&ledRED=1
Just have the handler on the ESP32 for the path /cmd look for the presence of each possible parameter and respond to it appropriately.

Java SIP client like present in android

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();
}
);

AWS Android Chat App

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!!

Libstreaming - use VLC as a RTSP client

I'm trying to use VLC as a RTSP client. The RTSP server is based on the libstreaming library. I'm using the code provided by the 1rst example:
// Sets the port of the RTSP server to 1234
Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putString(RtspServer.KEY_PORT, String.valueOf(1234));
editor.commit();
// Configures the SessionBuilder
SessionBuilder.getInstance()
.setSurfaceView(mSurfaceView)
.setPreviewOrientation(90)
.setContext(getApplicationContext())
.setAudioEncoder(SessionBuilder.AUDIO_NONE)
.setVideoEncoder(SessionBuilder.VIDEO_H264);
// Starts the RTSP server
this.startService(new Intent(this,RtspServer.class));
The android app starts; I try to access the stream using VLC (open a stream) and this URL:
rtsp://192.168.43.250:1234
The device is connected to the same network (I can ping it), but nothing happens in the android App and VLC displays a "connection failed" window.
Any idea where the problem is? Maybe a bad URL, but I can't found any detailled example of this situation.
It throws null pointer, check the logcat.
you have to provide the url as rtsp://ip:1234?h264=200-20-320-240
200 - buf
20 - fps
320 - resolution w
240 - resolution h
I had similar problems. Here is my solution.
Make sure you have imported the library as an imported module through android studio
Give your manifest the permission to use the resources needed
Use this code for you MainActivity:
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, RtspServer.CallbackListener, Session.Callback{
private final static String TAG = "MainActivity";
private SurfaceView mSurfaceView;
private Session mSession;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mSurfaceView = (SurfaceView) findViewById(R.id.surface);
// Sets the port of the RTSP server to 1234
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putString( RtspServer.KEY_PORT, String.valueOf(1234));
editor.commit();
// Configures the SessionBuilder
mSession = SessionBuilder.getInstance()
.setCallback(this)
.setSurfaceView((net.majorkernelpanic.streaming.gl.SurfaceView) mSurfaceView)
.setPreviewOrientation(90)
.setContext(getApplicationContext())
.setAudioEncoder(SessionBuilder.AUDIO_AAC)
.setAudioQuality(new AudioQuality(8000, 16000))
.setVideoEncoder(SessionBuilder.VIDEO_H264)
//.setVideoQuality(new VideoQuality(320,240,20,500000))
.build();
mSurfaceView.getHolder().addCallback(this);
((net.majorkernelpanic.streaming.gl.SurfaceView) mSurfaceView).setAspectRatioMode(net.majorkernelpanic.streaming.gl.SurfaceView.ASPECT_RATIO_PREVIEW);
String ip, port, path;
// Starts the RTSP server
this.startService(new Intent(this,RtspServer.class));
Log.d("test", "1");
mSession.startPreview(); //camera preview on phone surface
mSession.start();
}
#Override
public void onResume()
{
super.onResume();
mSession.stopPreview();
}
#Override
public void onDestroy()
{
super.onDestroy();
mSession.release();
mSurfaceView.getHolder().removeCallback(this);
}
//region ----------------------------------implement methods required
#Override
public void onError(RtspServer server, Exception e, int error) {
Log.e("Server", e.toString());
}
#Override
public void onMessage(RtspServer server, int message) {
Log.e("Server", "unkown message");
}
#Override
public void onBitrateUpdate(long bitrate) {
}
#Override
public void onSessionError(int reason, int streamType, Exception e) {
}
#Override
public void onPreviewStarted() {
}
#Override
public void onSessionConfigured() {
}
#Override
public void onSessionStarted() {
}
#Override
public void onSessionStopped() {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
//endregion
}
using VLC player open the open network stream and type
rtsp://the ip of android device:1234 <--this port is hard coded so don't change
When I worked with libstreaming & VLC I spent a lot of time with the same problem. The solution for me was to use other VLC version. For example, it worked for me on vlc ver. 1.0.5, but many other versions didn't play the stream.
))) the first example is a server (for the author of the library, the server is someone who accepts the stream and does not give)
you need to use 2 or 3 example ...
2 example is good because you only need a VLK player ...
find out your Ip (cmd-> ipconfig) (it's important to understand that the device must have an external ip address or is in the same network)
Specify the received ip address of the PC in mEditText (mSession.setDestination ();)
After launching the application, press the start button. The studio in the logs will return the contents to create the sdp format file (TAG, mSession.getSessionDescription ());
create a falix for example 1.sdp edit it by specifying the contents of getSessionDescription (remove extra spaces)
huge minutes then that we need to specify the ip of the one we want to send the stream to ...
 now the main thing! in any of the examples it does not turn out to simply enter rtsp: //192.168.43.250: 1234 and get the video !!! - 0)))))))
 
 In the Session class, you'll find mOrigin = "127.0.0.1"; ok SessionBuilder .... .setOrigin ("192.xxx.xxx.xx")
 Further your logic may suggest that you only need to find the port and maybe you will find SessionBuilder Session build () video.setDestinationPorts (5006);
 but this is not the port)))
 in this library there is no rtsp server implementation (I'm writing a server since it means that we want to raise the server for ip cam on the device)
 
 you can find the hint in the RtspClient class (pay attention to the author of the library, this is the one who gives it) and there the author writes to us
 
 * RFC 2326.
 * A basic and asynchronous RTSP client.
 RTSP client compatible with Wowza.
 * It implements Digest Access Authentication according to RFC 2069.

Sending DataMap in a background service android

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.

Categories