Blackberry check internet connection on device - blackberry

How do I check if the Internet connection is ON or OFF on a device?

You better check using
CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_DIRECT);
The CoverageInfo class provides some more types of coverage to check for. See http://www.blackberry.com/developers/docs/6.0.0api/net/rim/device/api/system/CoverageInfo.html

I think there is no direct way.
You just request for a server,if there is there is no internet not avilable at that time an exception is thrown, you catch it display an alert to the user.
Some thing like below:
try {
// request http
}
catch(IOException e) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("No Internet Connectivity");
//System.exit(0);
}
});
System.out.println(e);
}

Call this method, if it returns true then you've got connection. It checks to ensure you have enough battery for internet connection, your 3G or wireless is turned on and then you have enough signal.
public synchronized static boolean checkConnection() {
boolean returnVal = true;
if (DeviceInfo.getBatteryLevel() < 6) {
returnVal = false;
}
else if (RadioInfo.getState() == RadioInfo.STATE_OFF) {
returnVal = false;
}
else if (RadioInfo.getSignalLevel() == RadioInfo.LEVEL_NO_COVERAGE) {
returnVal = false;
}
return returnVal;
}

Here's what I use in my application, and it works just fine:
protected static boolean isOutOfServiceRange() {
return !RadioInfo.isDataServiceOperational();
}

Related

Appium checking if element is displayed

I'm using Appium for Android
the following works for clicking on the element
driver.findElement(By.xpath("//*[#resource-id='com.app.android:id/prelogin_signup']")).click();
But I am trying to check if an element is on the screen and I tried the following
if (driver.findElement(By.xpath("//*[#resource-id='com.app.android:id/prelogin_signup']")).isDisplayed()) {
System.out.println("FOUND");
} else {
System.out.println("NOT FOUND!");
}
but it returns an Exception saying
INFO: HTTP Status: '405' -> incorrect JSON status mapping for 'unknown error' (500 expected)
org.openqa.selenium.WebDriverException: Method is not implemented
How can I check to see if an element is on the screen?
You can try this, hope it helps
//If the element found, do as you want
if (driver.findElements(By.xpath("//*[#resource-id='com.app.android:id/prelogin_signup']")).size() > 0) {
System.out.println("FOUND");
} else {
System.out.println("NOT FOUND!");
}
you can surround your code with try catch block.
public boolean isElementDisplayed(){
try{
return driver.findElement(By.xpath("//*[#resource-id='com.app.android:id/prelogin_signup']")).isDisplayed();
}catch(Exception e){
//System.out.println(e);
return false;
}
}
you can also make the generic function to check if element is displayed.
public boolean isElementDisplayed(MobileElement element){
try{
return element.isDisplayed();
}catch(Exception e){
//System.out.println(e);
return false;
}
}
You may also try isDisplayed().
if (demoPage.proceedButton().isDisplayed() == true) {
System.out.println("BUTTON FOUND*****");
TestUtil.click(cartPage.proceedButton(), 10);
} else {
System.out.println("PROCEED BUTTON NOT FOUND!*********");
}
Note - I am using Page Factory model. Hence, demoPage.proceedButton() is used, you may use your locator in place of this declaration.

IncompatibleClassChangeError on Android Things

After updating to the latest Android Things preview, my app is crashing when
setting a callback on by button GPIO. I have the following button callback defined:
private class ButtonCallback extends GpioCallback {
#Override
public boolean onGpioEdge(Gpio gpio) {
boolean isPressed = false;
try {
isPressed = gpio.getValue();
} catch (IOException e) {
Log.w(TAG, "Error", e);
}
if (isPressed) {
...
}
return true;
}
}
I am registering it with the GPIO in the application as follows:
Gpio button = ...;
try {
button.registerGpioCallback(new ButtonCallback());
} catch (IOException e) {
Log.w(TAG, "Error configuring GPIO pins", e);
}
When I run my app, I get an IncompatibleClassChangeError and the app crashes:
java.lang.IncompatibleClassChangeError: Superclass com.google.android.things.pio.GpioCallback of com.google.android.things.example.MainActivity$ButtonCallback is an interface (...)
This code was working before, why has this started happening after the update?
Starting in Preview 7, many of the Peripheral I/O interfaces were converted from
abstract classes to interfaces. This was done to better facilitate testability
in apps, as interfaces are easier to mock.
Be sure to update your app to use the Preview 7 SDK:
dependencies {
compileOnly 'com.google.android.things:androidthings:0.7-devpreview'
}
Then modify your callback to implement the interface instead:
private class ButtonCallback implements GpioCallback {
#Override
public boolean onGpioEdge(Gpio gpio) {
boolean isPressed = false;
try {
isPressed = gpio.getValue();
} catch (IOException e) {
Log.w(TAG, "Error", e);
}
if (isPressed) {
...
}
return true;
}
}
Review the Android Things API reference
to verify if any of the other APIs you are calling have changed.

Implementing NetworkStatusBroadcastReceiver example

I'm attempting to implement a BroadcastReceiver that will tell me when the network status has changed. I'll be using that to sync local data back to the main server when I get internet connection back after losing it.
As a start I was looking at this example: http://fizzylogic.nl/2013/08/17/xamarin-android-by-example-monitoring-the-network-status/
public class NetworkStatusMonitor
{
private NetworkState _state;
public NetworkStatusMonitor ()
{
}
public NetworkState State {
get {
UpdateNetworkStatus ();
return _state;
}
}
public void UpdateNetworkStatus() {
_state = NetworkState.Unknown;
// Retrieve the connectivity manager service
var connectivityManager = (ConnectivityManager)
Application.Context.GetSystemService (
Context.ConnectivityService);
// Check if the network is connected or connecting.
// This means that it will be available,
// or become available in a few seconds.
var activeNetworkInfo = connectivityManager.ActiveNetworkInfo;
if (activeNetworkInfo.IsConnectedOrConnecting) {
// Now that we know it's connected, determine if we're on WiFi or something else.
_state = activeNetworkInfo.Type == ConnectivityType.Wifi ?
NetworkState.ConnectedWifi : NetworkState.ConnectedData;
} else {
_state = NetworkState.Disconnected;
}
}
}
public enum NetworkState
{
Unknown,
ConnectedWifi,
ConnectedData,
Disconnected
}
Then my broadcast receiver looks like this:
[BroadcastReceiver()]
public class NetworkStatusBroadcastReceiver: BroadcastReceiver {
public event EventHandler ConnectionStatusChanged;
public override void OnReceive (Context context, Intent intent)
{
if (ConnectionStatusChanged != null)
ConnectionStatusChanged (this, EventArgs.Empty);
}
}
Now my question is... Where do I initialize this and where do I put the following Start() and Stop() methods?
public event EventHandler NetworkStatusChanged;
public void Start ()
{
if (_broadcastReceiver != null) {
throw new InvalidOperationException (
"Network status monitoring already active.");
}
// Create the broadcast receiver and bind the event handler
// so that the app gets updates of the network connectivity status
_broadcastReceiver = new NetworkStatusBroadcastReceiver ();
_broadcastReceiver.ConnectionStatusChanged += OnNetworkStatusChanged;
// Register the broadcast receiver
Application.Context.RegisterReceiver (_broadcastReceiver,
new IntentFilter (ConnectivityManager.ConnectivityAction));
}
void OnNetworkStatusChanged (object sender, EventArgs e)
{
var currentStatus = _state;
UpdateNetworkStatus ();
if (currentStatus != _state && NetworkStatusChanged != null) {
NetworkStatusChanged (this, EventArgs.Empty);
}
}
public void Stop() {
if (_broadcastReceiver == null) {
throw new InvalidOperationException (
"Network status monitoring not active.");
}
// Unregister the receiver so we no longer get updates.
Application.Context.UnregisterReceiver (_broadcastReceiver);
// Set the variable to nil, so that we know the receiver is no longer used.
_broadcastReceiver.ConnectionStatusChanged -= OnNetworkStatusChanged;
_broadcastReceiver = null;
}
Sorry for the probably silly question but still new to Xamarin and Android.
I think following link is helpful. I get the notification when the network status changes.
networkstatusbroadcastreceiver See Bradley's answer on the bottom of the page.

Cancel a timer in BlackBerry - Java

I am working with a BlackBerry App that has a number of timers in it to schedule sending reports to the server platform. It is all working fine until I changed the logic to prioritize reports. Therefore, now I am checking if, for instance, Report A is switched on and the user activates Report B as well, then only Report B should go through and Report A should halt UNTIL B is activated. Once B is deactivated (timer cancelled), Report A should resume. However, even when the code loops in the cancel timer task code, Report A continues to go through while B is still activated.
FieldChangeListener reportingListener = new FieldChangeListener() {
public void fieldChanged(Field field, int context)
{
try {
if (field == slider) {
int i = slider.getValue();
if(i==0)
lblInterval.setText(1+" minute");
if(i==1)
lblInterval.setText(2+" minutes");
if(i==2)
lblInterval.setText(5+" minutes");
if(i==3)
lblInterval.setText(10+" minutes");
if(i==4)
lblInterval.setText(15+" minutes");
if(i==5)
lblInterval.setText(30+" minutes");
if(i==6)
lblInterval.setText(1+" hour");
if(i==7)
lblInterval.setText(2+" hours");
if(i==8)
lblInterval.setText(6+" hours");
if(i==9)
lblInterval.setText(12+" hours");
if(i==10)
lblInterval.setText(24+" hours");
setSliderPosition(i);
value=setLblIntervalValue(i);
value2=setGpsTimerIntervalValue(i);
gpsReportValue=lblInterval.getText();
gpsIntervalValue1=setGpsTimerIntervalValue(i);
}
if (PersistentStoreHelper.persistentHashtable.containsKey("image"))
{
boolean trackONOFFImage = ((Boolean) PersistentStoreHelper.persistentHashtable.get("image")).booleanValue();
if(trackONOFFImage==true)
{
if (PersistentStoreHelper.persistentHashtable.containsKey("panic"))
{
boolean panicImage = ((Boolean)PersistentStoreHelper.persistentHashtable.get("panic")).booleanValue();
if(panicImage==true)
{
MyScreen.currentlyReporting.setText("PANIC ALARM TRIGGERED");
if (PersistentStoreHelper.persistentHashtable.containsKey("tabTrackValid"))
{
boolean trackingTab = ((Boolean)PersistentStoreHelper.persistentHashtable.get("tabTrackValid")).booleanValue();
if(trackingTab==false)
{
trackSlider.cancel();
}
PersistentStoreHelper.persistentHashtable.put("tabTrackValid", Boolean.TRUE);
}
}
else
{
//int gpsIntervalValue1=setGpsTimerIntervalValue(i);
if (PersistentStoreHelper.persistentHashtable.containsKey("gpsTimerIntervalValue"))
{
String intervalValue=((String)PersistentStoreHelper.persistentHashtable.get("gpsTimerIntervalValue"));
if(gpsIntervalValue1==Integer.parseInt(intervalValue))
{
//do nothing
}
else
{
trackSlider = new TimerTask() {
public void run() {
try {
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run() {
//Dialog.alert("Invalid login details");
}
});
sendTrackingReport();
} catch (Exception e) {
Dialog.alert("Unable to track at the new interval set");
}
}
};
//trackSlider.run();
trackingTimerSlider.scheduleAtFixedRate(trackSlider , 0, gpsIntervalValue1);
PersistentStoreHelper.persistentHashtable.put("tabTrackValid", Boolean.FALSE);
}
}
}
}
}//this
}
} catch (IllegalStateException e) {
//Dialog.alert("CANCEL TRACK1");
e.printStackTrace();
} catch (NullPointerException e) {
//Dialog.alert("CANCEL TRACK2");
e.printStackTrace();
}
}
};
NOTE: Report A = Tracking. Report B = Panic. Panic has priority over Tracking. Slider is changing the timer interval value.
I debugged my code and while it goes into the loop and cancels the timer task of the requested report, I still see those reports going through. Am I not cancelling the timer correctly? Please advice.
From the TimerTask.cancel javadoc:
... If the task has been scheduled for repeated execution, it will never run again. (If the task is running when this call occurs, the task will run to completion, but will never run again.) ...
So to begin with, calling cancel from a thread does not immediatly stop the Timer thread as you can see.
Also you are creating a new Timer each time in your screen:
trackSlider = new TimerTask()
Thus it might be possible that if you create several instances of your screen during the app running, several timers of the same type will be created.

Connection being made, but content is unable to be retrieved from web service

public class ConsumeFactoryThread extends Thread {
private String url;
private HttpConnection httpConn;
private InputStream is;
private CustomMainScreen m;
private JSONArray array;
public ConsumeFactoryThread(String url, CustomMainScreen m){
System.out.println("Connection begin!");
this.url = url;
this.m = m;
}
public void finished(){
m.onFinish(array);
}
public void run(){
myConnectionFactory connFact = new myConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(url);
System.out.println("Connection factory!");
if(connDesc != null)
{
System.out.println("Connection not null!");
httpConn = (HttpConnection) connDesc.getConnection();
is = null;
try
{
final int iResponseCode = httpConn.getResponseCode();
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
System.out.println("Connection in run!");
// Get InputConnection and read the server's response
InputConnection inputConn = (InputConnection) httpConn;
try {
is = inputConn.openInputStream();
System.out.println("Connection got inputstream!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] data = null;
try {
data = IOUtilities.streamToBytes(is);
System.out.println("Connection got data!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String result = new String(data);
System.out.println("Connection Data: "+result);
try {
array = new JSONArray(result);
//finished();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
catch(IOException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
}
}
}
I'm using the blackberry torch 9800 simulator and hardware device for testing.
In the simulator I cannot retrieve the data over wifi, even though the connection to wifi is found. It works when the mobile network is enabled.
Now, when I replace my web service with the Twitter api, I get the data regardless of transport type. I tried adding ;deviceside=false to my url, but nothing. It's not https or anything.
I just want my web service accessed! I know nothing about this mds,bis,bes,bis_b junk.
EDIT:
Jeez. I'm realizing it may be my site. Not using the web service and just retrieving the page, www.example.com, I get nothing. But, google.com or any other site I use retrieves the html. Am I missing headers!?!
Try appending ;interface=wifi to the end of your URL, this will force the simulator to use your simulated Wi-Fi connection, which is your PC's network connection.
You will need to have setup Wi-Fi on the simulator by going to Manage Connections->Set Up Wi-Fi Network, then connect to Default WLAN Network.

Resources