How to properly open MidiDevice and send MidiMessage in Android? - java

I'm working on an app sending Midi messages from an Android smartphone to USB2.0-MIDI cable interface, which is connected with the phone via OTG cable. I'm still stuck on opening the MidiInput/Output Ports, without which I cannot move any further.
I've already tried everything that came to my mind. MIDI library isn't well covered, I did a huge research, read few Android Midi examples, but at the end here I am asking for help. My implementation seems to be correct, quite similar to what Android presents in the original MidiScope and MidiSynth samples.
At the moment every step of the process is logged. I found out that until the method device.openInputPort(port nr) is called, everything works right. After that nothing more happens. helperIN remains with null assigned, event though mOpenDevice is correctly opened with all the properties;
mManager.openDevice(midiDeviceInfo,
new MidiManager.OnDeviceOpenedListener() {
#Override
public void onDeviceOpened(MidiDevice device) {
Log.i("OnDeviceOpened", "before if");
if (device == null) {
Log.e("OnDeviceOpened", "cound not open" + midiDeviceInfo);
} else {
mOpenDevice = device;
Log.i("OnDeviceOpened", "opened: " + mOpenDevice.getInfo().getProperties().getString(MidiDeviceInfo.PROPERTY_NAME));
mListInput = new LinkedList<>();
MidiInputPort helperIN = null;
Log.i("OpenInputPort", "inPort Count: " + mOpenDevice.getInfo().getInputPortCount());
for (int i = 0; i < mOpenDevice.getInfo().getInputPortCount(); i++) {
Log.i("OpenInputPort", "Trying to open inPort nr: " + i); //last log seen
helperIN = device.openInputPort(i); //stuck right here!
Log.i("OpenInputPort", "Opened inPort nr: " + i); //this not seen
mListInput.add(helperIN);
if (helperIN == null) {
Log.e("openInputPort", "cound not open input port nr: " + i + " " + midiDeviceInfo.getPorts());
return;
}else
Log.i("openInputPort", "Port nr: " + i + "connected");
helperIN = null;
}
}
}
}, null);
Edit 1:
Logs:
after few hours, when in plugged the phone in to Android, to once again run the app and get the logs, firts thing I noticed was this. This is quite strange, seems like it took it lots of time to finally decide not to open the port.
04-01 09:13:43.733 7627-7639/com.example.anthonylp.midiandoridtest I/OpenInputPort: Opened inPort nr: 0
04-01 09:13:43.733 7627-7639/com.example.anthonylp.midiandoridtest E/openInputPort: cound not open input port nr: 0
[Landroid.media.midi.MidiDeviceInfo$PortInfo;#e7303d4
The actual logs are here:
04-01 09:42:11.704 3712-3712/com.example.anthonylp.midiandoridtest I/MidiWhenAdded: Class created
04-01 09:42:52.788 3712-3712/com.example.anthonylp.midiandoridtest I/MidiĀ Info: Name: null
Name: USB2.0-MIDI
04-01 09:42:52.788 3712-3712/com.example.anthonylp.midiandoridtest I/openMidiDevice: midiDeviceInfo not null
04-01 09:42:52.789 3712-3741/com.example.anthonylp.midiandoridtest I/OnDeviceOpened: before if
opened: USB2.0-MIDI
04-01 09:42:52.789 3712-3741/com.example.anthonylp.midiandoridtest I/OpenInputPort: inPort Count: 2
Trying to open inPort nr: 0
Nothing more seems to come out of it.
I expect the code to open the device MidiInputPort and assign it to helperIN, after that add it to mListInput.
Thanks a lot for help!

Related

Continues Internet Connection Checking in Android App [Checking Availability of Internet]

Before answer or taking any action just by seeing the question title please read description carefully, I am trying to do this yesterday and today a full day and night but I couldn't find any acceptable solution. Some are deprecated from android some are not working, some are just checking internet is just connected or not. But that's not what I am asking for.
I have applied many Stack Overflow answers in this regard but nothing is working perfectly. The functionality I am asking for is,
say MathActivity.java and activity_math.xml is a page loaded after clicking a button from mainActivity.java. When MathActivity.java is starting after clicking the button its primarily can check active internet connection via the ping method. Though its not working properly,
public boolean checkIntCON() {
try {
Process ipProcess = Runtime.getRuntime().exec("/system/bin/ping -c 1 8.8.8.8");
return (ipProcess.waitFor() == 0);
}
catch (IOException e) { e.printStackTrace(); }
catch (InterruptedException e) { e.printStackTrace(); }
return false;
}
But its check just one time when I am entering [I did that work but I don't want that], say user is reading a pdf in activity_math.xml and when user reading this user turned off internet connection, I am also able to listen that functionality when user turn off connection this would be ok but if user again turn on data with internet unavailability then I can't listen this .
I want to get recent and maximum device supported solution to check in continues internet connection. say user is reading a pdf, after five minutes I want to check if the user have an active internet connection or not. Connection should be must transferrable internet connection. I have found AsyncTask solution but its deprecated. The main focus is I want to check user active internet connection after a certain interval.
Here is an image to explain more,
Is there any solution? If any please try to give me in detail code that i just want to copy and paste in project. I have visited all in stack overflow again I am mentioning.
Pass context and call the function, I think this is what you are looking for.
public static boolean isConnected(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
Log.d("VIP", "isConnected: " + capabilities.getTransportInfo() + " down stream " + capabilities.getLinkDownstreamBandwidthKbps() +
" up stream " + capabilities.getLinkUpstreamBandwidthKbps() + " Cellular " + capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
+ " WiFi " + capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) + " Ethernet " + capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET));
return capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET);
} else {
NetworkInfo networkInfo = Objects.requireNonNull(connectivityManager).getActiveNetworkInfo();
boolean b = networkInfo != null && networkInfo.isConnected() && networkInfo.getDetailedState() != NetworkInfo.DetailedState.VERIFYING_POOR_LINK;
Log.d("VIP", "isConnected: else is connected " + b);
return b;
}
}

phonegap displaying text in native textbox

I'm making an android app which uses bluetooth using phonegap and I'm having issues handling code because it get's called every 100ms.
I want to try if the issue occurs because my phonegap javascript code is to long causing delays.
To try this I want to dispaly the received message using a native textbox.
Is this possible? and How would I do this?
Thanks
Martijn
PS: I've tried using Toast but since I want to change the displayed value every 100ms this doesn't work.
Code
upon receiving a message this is the order the code is processed
bytes = mmInStream.read(buffer);
s_message = new String(buffer, 0, bytes);
String[] strArray = s_message.split(",");
mHandleReceivedThread = new HandleReceivedThread(strArray);
mHandleReceivedThread.start();
In the HandleReceivedThread:
if(strArrayReceived[0].startsWith("Pressure"))
{
if(strArrayReceived[1].contains("Pressure"))
{
double Pressure = Double.parseDouble(strArrayReceived[1].replace("Pressure", ""));
double PressureResult = Pressure/10;
String PressureValue = String.valueOf(PressureResult);
webView.sendJavascript("PressureValue = " + Pressure + ";");
webView.sendJavascript("document.getElementById('Pressure').innerHTML = " + PressureValue + ";");
Log.e(TAG, "Message fail: " + strArrayReceived[1] );
}
else
{
double Pressure = Double.parseDouble(strArrayReceived[1]
double PressureResult = Pressure/10;
String PressureValue = String.valueOf(PressureResult);
webView.sendJavascript("PressureValue = " + Pressure + ";");
webView.sendJavascript("document.getElementById('Pressure').innerHTML = " + PressureValue + ";");
}
}
this is basically what happens.
And this happens every 100ms , and for some reason the displaying of the Value has lag and sometimes the received message (which should be "Pressure,1500" , or a different value) is Pressure,1500Pressure , causing errors (which I've managed to fix). but this still isn't optimal.
The message is send correctly and if I use a simple chat app they are received correctly.
if there is anything else I should supply , just ask ;-)

Can an Android Expert Explain Strange USB Host Behavior

I am writing an Android application to read input from a HID USB foot pedal (press the pedal, get a message, do something).
The UsbManager is not recognizing the device. The foot pedal may be throwing an error in Android kernel when it plugs in, because I see this error message in the logcat:
"EventHub could not get driver version for /dev/input/mouse0, not a typewriter"
However, I know the foot pedal works, because when I plug it in and press it, it changes the focus to the next button on the activity... So I know it is communicating with my Nexus tablet and apparently its default action is to move the focus to the next button/object. I don't think there are any problems with my code, since it will recognize other USB devices, just not this foot pedal. I can actually tell when it's pressed by checking for when the focus changes, but that won't work for what I want since this app will run in the background as a service. I've tried setting an intent filter for this specific USB device (I know its product id and vendor id). However, it still shows no connected devices and the pop-up message that is supposed to ask the user to confirm launching the application never shows up. I've tried just listing all the connected USB devices as well, but I always get an empty list.
Is there any way to intercept input from this device so I can tell when the foot pedal gets pressed, even though Android's USB Manager will not recognize it?
For completeness, here is my code. I am testing on a Galaxy Nexus 10 tablet:
public int list_usb_devices()
{
int device_count = 0;
UsbManager mUsbManager;
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
String LOG_TAG = "USB";
for (UsbDevice device : mUsbManager.getDeviceList().values()) {
//This code is never reached...
Log.d(LOG_TAG, "Detected device: " + device.toString());
Log.d(LOG_TAG, "Model: " + device.getDeviceName());
Log.d(LOG_TAG, "Id: " + device.getDeviceId());
Log.d(LOG_TAG, "Class: " + device.getDeviceClass());
Log.d(LOG_TAG, "Protocol: " + device.getDeviceProtocol());
Log.d(LOG_TAG, "VendorId: " + device.getVendorId());
Log.d(LOG_TAG, "ProductId: " + device.getProductId());
CharSequence text = device.toString();
show_toast(text);
device_count++;
}
return device_count;
}
I did some research in the Android source and it seems that all HID boot devices (mouse, keyboard etc.) are blacklisted and can therefore not be accessed using the USBManager API.
Here is the relevant part from the UsbHostManager.java , see here: http://grepcode.com/file_/repository.grepcode.com/java/ext/com.google.android/android/4.4.2_r1/com/android/server/usb/UsbHostManager.java/?v=source
/* returns true if the USB device should not be accessible by applications */
private boolean isBlackListed(int clazz, int subClass, int protocol) {
// blacklist hubs
if (clazz == UsbConstants.USB_CLASS_HUB) return true;
// blacklist HID boot devices (mouse and keyboard)
if (clazz == UsbConstants.USB_CLASS_HID &&
subClass == UsbConstants.USB_INTERFACE_SUBCLASS_BOOT) {
return true;
}
return false;
}

Server does not respond directly to my commands

First of all, I'll admit I am new to this and I've probably just forgotten to set an option somewhere to the correct variable, but my Googling has failed me and I have no idea what to do, so I was hoping to get some help.
I have based this on the SecureChat example, it can be located here: http://netty.io/docs/unstable/xref/org/jboss/netty/example/securechat/package-summary.html
And the difference I have made, have been only in the SecureChatServerHandler. More precisely in the messageRecieved block:
#Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
// Convert the message to a string
String request = (String) e.getMessage();
System.out.println("Message recieved: " + request);
if (request.equalsIgnoreCase("clients")) {
channels.write("We currently have: " + channels.size() + " clients");
} else if (request.toLowerCase().equals("koko"))
for (Channel c : channels) {
if (c == e.getChannel())
c.write("HELLO WORLD");
}
else {
// Then send it to all channels, but the current one.
for (Channel c : channels)
if (c != e.getChannel())
c.write("[" + e.getChannel().getRemoteAddress() + "] " + request + "\n");
else
c.write("[you] " + request + "\n");
}
if (request.equalsIgnoreCase("bye"))
e.getChannel().close();
}
If I send a normal message that is getting broadcasted, everything works. But if I send a command, like clients or koko, I get no response, until I press enter again and send a empty message. First then I get the response back.
C:\Device Manager\Application Server\Examp
les\SecureChat\SecureChatClient\bin>java -jar client.jar 127.0.0.1 8080
UNKNOWN SERVER CERTIFICATE: CN=securechat.example.netty.gleamynode.net, OU=Contr
ibutors, O=The Netty Project, L=Seongnam-si, ST=Kyunggi-do, C=KR
Welcome to Electus secure chat service!
Your session is protected by TLS_DHE_RSA_WITH_AES_128_CBC_SHA cipher suite
You are the 1th user
koko<ENTER>
<PRESS ENTER AGAIN>
HELLO WORLD[you]
clients<ENTER>
<AND ENTER ONCE AGAIN>
We currently have: 1 clients[you]
What I don't understand, and don't want, is the -pressing of enter button twice- thing. It seems highly inlogical and it is irritating. I didn't have these problem with the Telnet Example.
Thank you for your time.
Regards,
Aldrian.
This is one of those humiliating times where you just forgot one small detail, and that messes everything up.
if (request.equalsIgnoreCase("clients")) {
channels.write("We currently have: " + channels.size() + " clients /n"); // Forgot /n here
} else if (request.toLowerCase().equals("koko"))
for (Channel c : channels) {
if (c == e.getChannel())
c.write("HELLO WORLD /n"); // <- Forgot /n here as well
}

Why do the outputs differ when I run this code using NetBeans 6.8 and Eclipse? [duplicate]

This question already has an answer here:
Closed 12 years ago.
Possible Duplicate:
Why do the outputs differ when I run this code using NetBeans 6.8 and Eclipse?
When I am running the following code using Eclipse and NetBeans 6.8. I want to see the available COM ports on my computer. When running in Eclipse it is returning me all available COM ports, but when running it in NetBeans, it does not seem to find any ports ..
public static void test() {
Enumeration lists=CommPortIdentifier.getPortIdentifiers();
System.out.println(lists.hasMoreElements());
while (lists.hasMoreElements()) {
CommPortIdentifier cn =
(CommPortIdentifier)lists.nextElement();
if ((CommPortIdentifier.PORT_SERIAL==cn.getPortType())) {
System.out.println(
"Name is serail portzzzz " +
cn.getName()+
" Owned status " +
cn.isCurrentlyOwned());
try {
SerialPort port1=(SerialPort)cn.open("ComControl",800000);
port1.setSerialPortParams(
9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
System.out.println("Before get stream");
OutputStream out=port1.getOutputStream();
InputStream input=port1.getInputStream();
System.out.println("Before write");
out.write("AT".getBytes());
System.out.println("After write");
int sample=0;
//while((( sample=input.read())!=-1)){
System.out.println("Before read");
//System.out.println(input.read() + "TEsting ");
//}
System.out.println("After read");
System.out.println(
"Receive timeout is " +
port1.getReceiveTimeout());
}
catch(Exception e) {
System.err.println(e.getMessage());
}
}
else {
System.out.println(
"Name is parallel portzzzz " +
cn.getName() +
" Owned status " +
cn.isCurrentlyOwned() +
cn.getPortType() +
" ");
}
}
}
Output with Netbeans,
false
Output using Eclipse,
true
Name is serail portzzzz COM1 Owned status false
Before get stream
Before write
After write
Before read
After read
Receive timeout is -1
Name is serail portzzzz COM2 Owned status false
Before get stream
Before write
After write
Before read
After read
Receive timeout is -1
Name is parallel portzzzz LPT1 Owned status false2
Name is parallel portzzzz LPT2 Owned status false2
An initial guess would be that the library you use use native code enclosed in a DLL and that code cannot be found giving an error earlier you have missed, and the code falls back to a dummy behaviour.
I would have a closer look at the initialization code to see what happens there.

Categories