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;
}
}
Related
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!
I am working on Parrot AR. Drone project. The libraries are downloaded and implemented in this project from JavaDrone website (https://code.google.com/p/javadrone/downloads/list). However, although I did included the all the correct libraries and make the right class call to get the method, it still cannot return me the correct information. All the results returned appeared to be "false". Any idea what happening on this code? Please help me :(
So what I did is I have 2 buttons : (i) connect (ii) take off buttons. The Connect button function is for establish connection to drone while Take off button is used for make the drone fly move a bit and return me the drone's NAV navigation data. Sadly all the returned NAV data appears not working.
Note : This code is working fine upon code compilation. But it just cannot return me the correct & valid NAV data from drone.
private void jButtonConnectActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("Connect?");
drone = new ARDrone();
data = new NavData();
drone.playLED(10,10,10);
drone.connect();
drone.clearEmergencySignal();
System.err.println("Ready to connect!!");
// Wait until drone is ready
drone.waitForReady(CONNECT_TIMEOUT);
System.err.println("Drone State: " + drone.getState());
// do TRIM operation
drone.trim();
System.err.println("Congratulation! You have connected to Drone!");
System.out.println("You can issue flight commands now!");
batteryStatus.setText("0" + "%");
batteryStatus.setForeground(Color.ORANGE);
batteryStatus.setText("" + data.getBattery());
}
private void jButtonTakeOffActionPerformed(java.awt.event.ActionEvent evt) {
System.err.println("Current Drone State : " + drone.getState().toString());
System.err.println("Taking off");
drone.takeOff();
Thread.sleep(4000);
System.err.println("**********\nMOVE\n**********");
drone.move(0.0f, 150.5f, 500.0f, 0.0f);
Thread.sleep(1000);
System.err.println("******************************************");
System.err.println("Drone Infomation");
System.err.println("Battery Too High ? " + data.isBatteryTooHigh());
System.err.println("Battery Too Low ? " + data.isBatteryTooLow());
System.err.println("Drone Flying ? " + data.isFlying());
System.err.println("Control Received ? " + data.isControlReceived());
System.err.println("Motor Down ? " + data.isMotorsDown());
System.err.println("Not Enough Power ?" + data.isNotEnoughPower());
System.err.println("Trim Received ? " + data.isTrimReceived());
System.err.println("Trim Running? " + data.isTrimRunning());
System.err.println("Trim succeded? " + data.isTrimSucceeded());
System.err.println("PIC Number OK? "+ data.isPICVersionNumberOK());
System.err.println("******************************************");
Thread.sleep(5000);
drone.sendAllNavigationData();
drone.land();
}
Output :
******************************************
Drone Infomation
Battery Life: 0.0%
Battery Too High ? false
Battery Too Low ? false
Drone Flying ? false
Control Received ? false
Motor Down ? false
Not Enough Power ?false
Trim Received ? false
Trim Running? false
Trim succeded? false
PIC Number OK? false
********************************************
Update:
What I did was followed John's suggestion. I did implemented all the neccessary methods and NavDataListener for getting the NavData from drone.
import com.codeminders.ardrone.ARDrone;
import com.codeminders.ardrone.ARDrone.VideoChannel;
import com.codeminders.ardrone.NavData;
import com.codeminders.ardrone.NavDataListener;
public class arDrone extends javax.swing.JFrame implements Runnable, NavDataListener{
public ARDrone drone;
public NavData data = new NavData();
public arDrone(String text) {
//FreeTTS speech text
this.text=text;
}
public arDrone() {
initComponents();
setIcon();
initDrone();
}
private void initDrone() {
try {
drone = new ARDrone();
data = new NavData();
drone.addNavDataListener(this);
} catch (UnknownHostException ex) {
System.err.println(ex);
return;
}
}
public void navDataReceived(NavData nd) {
System.err.println("Testing navDataReceived is running...");
updateBatteryStatus(nd.getBattery());
this.flying.set(nd.isFlying());
}
private void updateBatteryStatus(final int value) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
batteryStatus.setText(value + "%");
if (value < 15) {
batteryStatus.setForeground(Color.RED);
} else if (value < 50) {
batteryStatus.setForeground(Color.ORANGE);
} else {
batteryStatus.setForeground(Color.GREEN);
}
}
});
}
The problem is that you are not doing anything to actually get navdata. You can't just create a NavData object and hope it gets filled in with valid data--It won't.
You need to use the com.codeminders.ardrone.NavDataListener interface.
Implement the NavDataListener interface, and the
navDataReceived method.
Add your listener using the ARDrone
method addNavDataListener.
In your navDataRecieved method
you will receive a NavData object with valid telemetry data.
Do you set the Drone IP address? According to sources the default IP for the drone is 192.168.1.1.
You can call another constructor to set the IP:
drone = new ARDrone(InetAddress.getByName("xxx.xxx.xxx.xxx"));
replace xxx.xxx.xxx.xxx with the actual drone IP.
I am setting up and testing in-app billing. I managed to purchase the android.test.purchased, and it did what it should. But now I need to consume it to continue my testing. The problem is that I can't reach the inventory.
When this is called I get the result.isFaliure() is called and I can't get the inventory.
IabHelper.QueryInventoryFinishedListener _gotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
#Override
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
if (_iabHelper == null) return;
if (result.isFailure()) {
Log.d(TAG, "Failed to query inventory: " + result);
return;
}
Log.d(TAG, "Query inventory was successful.");
Purchase premiumPurchase = inventory.getPurchase(SKU_PREMIUM);
_isPremium = (premiumPurchase != null && verifyDeveloperPayload(premiumPurchase));
Log.d(TAG, "User is " + (_isPremium ? "PREMIUM" : "NOT PREMIUM"));
update();
}
};
It logs the error message
Failed to query inventory: IabResult: Error refreshing inventory
(querying owned items). (response: -1003:Purchase signature
verification failed)
The android.test.purchased is still owned - it won't let me buy it again. My phone has network connection so it's not that.
I have NOT uploaded a signed APK to Google Play, does that matter even if I test with googles static ID's?
Solved it...
It seems there are problems with the static purchase ID's.
Here's a sollution I found in THIS thread:
If you have used the android.test.purchased then one way to get rid of the error is to do the following:-
1. Edit Security.java and change the "return false" line in the
verifyPurchase to "return true" - this is temporary, we'll be
putting it back in a minute.
2. In your QueryInventoryFinishedListener, after the "if
(result.isFailure()) {...}" lines add the following to consume and
get rid of your never ending android.test.purchased item:-
if (inventory.hasPurchase(SKU_ANDROID_TEST_PURCHASE_GOOD)) {
mHelper.consumeAsync(inventory.getPurchase(SKU_ANDROID_TEST_PURCHASE_GOOD),null);
}
3. Run your app so the consunmeAsync happens, this gets rid of the
"android.test.purchased" item on the server.
4. Remove the consumeAsync code (or comment it out). Back in the
Security.java, change the "return true" back to "return false".
I found the answer here:
"Here's a recommendation: Make sure that your Billing Key (base64EncodedPublicKey) is properly saved. That was my problem, after all that..."
base64EncodedPublicKey was from another aplication...
It was solution for me.
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;
}
I have this classes for my app:
NewsApp.java
ScreenApp.java
Item.java
ui/TableList.java
The app retrieve a list of links from a webservice (.net), I use KSoap Library (as Reference project).
I use JDE 4.5 for develop, because with Eclipse I cant use the method "setRowHeight(index, int)" of ListField class, then I need use JDE 4.5
Ok, I compile the app (F7 key), and run in simulator (F5 key).
In simulator, go to the icon app, and try to open... nothing happends... the app not open... are strange... no error message (ScreenApp.java line 57)... but... if I few more minutes... I see the error message (ScreenApp.java line 57)... I think maybe is because the app try connect...
Later... I think is because not exists a internet connection in simulator (I see EDGE in the top of simulator... is strange), I stop de simulator, open MDS, and run simulator again (F5 key), and now works... the list show correctly... and I can open the links in the blackberry browser.
Now... I put all compiled files in same directory, create a ALX file:
NewsApp.alx
And install this app on device, the installation works ok, I go to the list of applications on device (8520), Open the app and I see the connection message (ScreenApp.java line 57);
I dont understand why ? in this phone (8520) I have EDGE connection with my carrier, I have the WIFI active... I can browse in any page (default browser)... but my app cant retrieve information from webservice... :(
Anybody help me please ?
You need to use Different connection parameter at the end of the url when application run on the device.
For ex. in case of wifi, you need to append ;interface=wifi" at the end of the URL.
Detail code is: you need to call getConnectionString() to get the connection sufix according to device network. I hope this will solve your problem.
/**
* #return connection string
*/
static String getConnectionString()
{
// This code is based on the connection code developed by Mike Nelson of AccelGolf.
// http://blog.accelgolf.com/2009/05/22/blackberry-cross-carrier-and-cross-network-http-connection
String connectionString = null;
// Simulator behavior is controlled by the USE_MDS_IN_SIMULATOR variable.
if(DeviceInfo.isSimulator())
{
// logMessage("Device is a simulator and USE_MDS_IN_SIMULATOR is true");
connectionString = ";deviceside=true";
}
// Wifi is the preferred transmission method
else if(WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
// logMessage("Device is connected via Wifi.");
connectionString = ";interface=wifi";
}
// Is the carrier network the only way to connect?
else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT)
{
//logMessage("Carrier coverage.");
String carrierUid = getCarrierBIBSUid();
if(carrierUid == null)
{
// Has carrier coverage, but not BIBS. So use the carrier's TCP network
// logMessage("No Uid");
connectionString = ";deviceside=true";
}
else
{
// otherwise, use the Uid to construct a valid carrier BIBS request
// logMessage("uid is: " + carrierUid);
connectionString = ";deviceside=false;connectionUID="+carrierUid + ";ConnectionType=mds-public";
}
}
// Check for an MDS connection instead (BlackBerry Enterprise Server)
else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS)
{
// logMessage("MDS coverage found");
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid bugging the user unnecssarily.
else if(CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE)
{
//logMessage("There is no available connection.");
}
// In theory, all bases are covered so this shouldn't be reachable.
else
{
//logMessage("no other options found, assuming device.");
connectionString = ";deviceside=true";
}
return connectionString;
}
/**
* Looks through the phone's service book for a carrier provided BIBS network
* #return The uid used to connect to that network.
*/
private static String getCarrierBIBSUid()
{
ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for(currentRecord = 0; currentRecord < records.length; currentRecord++)
{
if(records[currentRecord].getCid().toLowerCase().equals("ippp"))
{
if(records[currentRecord].getName().toLowerCase().indexOf("bibs") >= 0)
{
return records[currentRecord].getUid();
}
}
}
return null;
}