LocationUpdate method getting called too frequently on Blackberry - blackberry

I have a 3 GSM phones and a 3 verizon (CDMA) phones. I have a BB application in which the location listener is set to a 5 minute interval.
For 2 of the verizon phones the application's location update method gets called frequently. For the rest, the location listener gets called at a regular 5 minute interval.
What could be causing this difference in behavior?
public synchronized void locationUpdated(LocationProvider locationProvider, Location location) {
if (enabled) {
if (blackberryProvider != null) {
try {
constructCriteria(GPSInfo.GPS_MODE_CELLSITE);
gpsUpdate();
} catch (LocationException e) {
log stuff//
}
}
}
}
private void gpsUpdate() throws LocationException, InterruptedException {
try {
String gpsMode = null;
if (bbCriteria.getMode() == GPSInfo.GPS_MODE_CELLSITE) {
gpsMode = "cellsiteMode";
}
if (gpsMode == "cellsiteMode" && gpsMode.length() > 0 && bbProvider != null) {
// variable declaration
try {
bbLocation = (BlackBerryLocation) bbProvider.getLocation(10);
} catch (LocationException e) {
bbLocation = null;
}
if (bbLocation != null) {
// do stuff
// store location in the database
}
}
}
}
}
}
private void constructCriteria(final int mode) {
blackberryCriteria = null;
blackberryProvider = null;
blackberryCriteria = new BlackBerryCriteria();
blackberryCriteria.setSatelliteInfoRequired(true, false);
if (mode == GPSInfo.GPS_MODE_CELLSITE) {
setCriteraForCellSite();
}
try {
blackberryProvider = (BlackBerryLocationProvider) LocationProvider.getInstance(blackberryCriteria);
if (iLocationListner == null) {
iLocationListner = new ILocationListner();
blackberryProvider.setLocationListener(iLocationListner, locationInterval == 0 ? 300 : locationInterval, -1, -1);
} else {
blackberryProvider.setLocationListener(iLocationListner, locationInterval == 0 ? 300 : locationInterval, -1, -1);
}
} catch (LocationException lex) {
Logger.log("LocationEventSource constructor", lex);
return;
}
}

You are setting your criteria to update every 300 seconds if locationInterval == 0 or at the default rate (once per second) otherwise. Is this really what you want? Where is locationInterval initialized? How does its value change as the program runs?

Related

Azure Mobile Service calls hangs

Using Xamarin.Forms app. When mobile data connection fluctuates on Android devices, e.g. network from 3G to 2G connection, or vice versa - the call seems to get hung somewhere.
This is the Azure API call :
public Task<ObservableCollection<Models.Item>> GetItemsByID(string tenantID, string auth_token)
{
return Task.Factory.StartNew(() =>
{
var res = RestClient.Get<ObservableCollection<Models.Item>>(HttpWebRequest.Create(string.Format(EndPointsList.GetItemsUrl + "tenantID={0}", tenantID)),auth_token);
return res ;
});
}
We initiate the System.Net.WebRequest here :
public static T Get<T>(WebRequest request, string auth_token, string requestData = null)
{
string result = string.Empty;
request.ContentType = "application/json";
request.Headers["ZUMO-API-VERSION"] = "2.0.0";
if (auth_token.StartsWith("Bearer"))
request.Headers["Authorization"] = auth_token;
else {
request.Headers["x-access_type"] = "offline";
request.Headers["x-zumo-auth"] = auth_token;
}
try
{
WebResponse webResponse = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null).Result;
using (var streamReader = new StreamReader(webResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
var typ = typeof(T);
if (
typ == typeof(String)
|| typ == typeof(float)
|| typ == typeof(Decimal)
|| typ == typeof(Int16)
|| typ == typeof(Int32)
|| typ == typeof(Int64)
)
{
return (T)Convert.ChangeType(result, typeof(T), null);
}
return result.FromJson<T>();
}
catch (AggregateException agEx)
{
AggregateException(agEx);
return result.FromJson<T>();
}
catch (Exception ex)
{
return result.FromJson<T>();
}
}
This is the call from ViewModel
public async Task GetAllItems()
{
try
{
if (!this.IsInternetConnectionAvailable())
{
await this.CurrentContentPage.DisplayAlert("", AppResources.InternetConnectionNotAvailable, AppResources.Ok);
return;
}
this.ProgressBar.ShowProgress(AppResources.Loading);
ItemList = await this.ItemService.GetItemsByID(App.Locator.Login.LoggedInUser.TenantID.ToString(),Settings.AuthToken);
if (ItemList != null)
{
for (int i = 0; i < this.ItemList.Count; i++)
{
ItemList[i].RowColor = (i % 2 == 0 ? Theme.EvenRowColor : Theme.OddRowColor);
}
}
RaisePropertyChanged("ItemList");
}
catch (Exception ex)
{
ExceptionHandler.HandleException(CurrentContentPage, ex);
}
finally
{
this.ProgressBar.Dismiss();
}
}
In actual case here - the ProgressBar will kept on be displayed on the device, though its in Finally block. User have to kill the application to make it work again.
And we're unsuccessful to reproduce this back in lab. It only happens on field during intermittent connections.
Any abnormalities in the code? If not, how can we capture this in application log.

How to add text input field in cocos2d.Android cocos sharp?

I am trying to get CCTextFieldTTF to work in cocos sharp with Xamarin for an android application. But can't get hold of this for the life of me. Could not find any documentation on cocos sharp API either. Does anyone know how to use this class to render a text area in an android application? The reason I am asking is in a xamarin forum I saw someone saying that this does not work in the API yet. Any help would be highly appreciated. Thanks in advance.
I have this working in android
Here is the sample code:
Create a node to track the textfield
CCTextField trackNode;
protected CCTextField TrackNode
{
get { return trackNode; }
set
{
if (value == null)
{
if (trackNode != null)
{
DetachListeners();
trackNode = value;
return;
}
}
if (trackNode != value)
{
DetachListeners();
}
trackNode = value;
AttachListeners();
}
}
//create the actual input textfield
var textField = new CCTextField(string.Empty, "Somefont", 25, CCLabelFormat.SystemFont);
textField.IsColorModifiedByOpacity = false;
textField.Color = new CCColor3B(Theme.TextWhite);
textField.BeginEditing += OnBeginEditing;
textField.EndEditing += OnEndEditing;
textField.Position = new CCPoint (0, 0);
textField.Dimensions = new CCSize(VisibleBoundsWorldspace.Size.Width - (160 * sx), vPadding);
textField.PlaceHolderTextColor = Theme.TextYellow;
textField.PlaceHolderText = Constants.TextHighScoreEnterNamePlaceholder;
textField.AutoEdit = true;
textField.HorizontalAlignment = CCTextAlignment.Center;
textField.VerticalAlignment = CCVerticalTextAlignment.Center;
TrackNode = textField;
TrackNode.Position = pos;
AddChild(textField);
// Register Touch Event
var touchListener = new CCEventListenerTouchOneByOne();
touchListener.OnTouchBegan = OnTouchBegan;
touchListener.OnTouchEnded = OnTouchEnded;
AddEventListener(touchListener);
// The events
bool OnTouchBegan(CCTouch pTouch, CCEvent touchEvent)
{
beginPosition = pTouch.Location;
return true;
}
void OnTouchEnded(CCTouch pTouch, CCEvent touchEvent)
{
if (trackNode == null)
{
return;
}
var endPos = pTouch.Location;
if (trackNode.BoundingBox.ContainsPoint(beginPosition) && trackNode.BoundingBox.ContainsPoint(endPos))
{
OnClickTrackNode(true);
}
else
{
OnClickTrackNode(false);
}
}
public void OnClickTrackNode(bool bClicked)
{
if (bClicked && TrackNode != null)
{
if (!isKeyboardShown)
{
isKeyboardShown = true;
TrackNode.Edit();
}
}
else
{
if (TrackNode != null)
{
TrackNode.EndEdit();
}
}
}
private void OnEndEditing(object sender, ref string text, ref bool canceled)
{
//((CCNode)sender).RunAction(scrollDown);
Console.WriteLine("OnEndEditing text {0}", text);
}
private void OnBeginEditing(object sender, ref string text, ref bool canceled)
{
//((CCNode)sender).RunAction(scrollUp);
Console.WriteLine("OnBeginEditing text {0}", text);
}
void AttachListeners()
{
// Attach our listeners.
var imeImplementation = trackNode.TextFieldIMEImplementation;
imeImplementation.KeyboardDidHide += OnKeyboardDidHide;
imeImplementation.KeyboardDidShow += OnKeyboardDidShow;
imeImplementation.KeyboardWillHide += OnKeyboardWillHide;
imeImplementation.KeyboardWillShow += OnKeyboardWillShow;
imeImplementation.InsertText += InsertText;
}
void DetachListeners()
{
if (TrackNode != null)
{
// Remember to remove our event listeners.
var imeImplementation = TrackNode.TextFieldIMEImplementation;
imeImplementation.KeyboardDidHide -= OnKeyboardDidHide;
imeImplementation.KeyboardDidShow -= OnKeyboardDidShow;
imeImplementation.KeyboardWillHide -= OnKeyboardWillHide;
imeImplementation.KeyboardWillShow -= OnKeyboardWillShow;
imeImplementation.InsertText -= InsertText;
}
}
This is all taken from the link below but needed a bit of additional work to get it working on each platform.
https://github.com/mono/cocos-sharp-samples/tree/master/TextField

Xamarin iOS Bluetooth Low Energy - CBPeripheral.UpdatedCharacteristicValue reading TX characteristic shows unexpected data

I recently received a BLE device for Bluetooth to Serial. It uses TruConnect and I'm trying to get it to communicate with my serial device. The serial device receives communication over a serial cable and echoes back anything that is sent to it as well as any results from a command that is sent.
Right now I'm simply trying to send TruConnect commands to the BLE device to check the current baud rate that the BLE device is set for.
I wrote some code based on this TruConnect guide that I found:
https://truconnect.ack.me/1.5/apps/communicating_via_ble#reading_from_a_truconnect_device_serial_interface.
The problem seems to be that whenever I try to read anything from the tx characteristic when there should be data, the data is not right.
Setting up CBPeripheral events:
private void setupPerif(CBPeripheral perf)
{
selectedPeripheral = perf;
selectedPeripheral.UpdatedCharacterteristicValue += (sender, e) =>
{
var c = e.Characteristic;
if (c != null)
{
var uuid = c.UUID.ToString(true).ToLower();
if (uuid == UUID_RX)
{
//
}
else if (uuid == UUID_TX)
{
// expecting bytes to contain valid response data
// it almost always contains twenty 0s.
byte[] bytes = c.Value.Where(i => i != 13).ToArray();
var invalidBytes = c.Value.Where(i => i > 127).ToArray();
var nonZeros = c.Value.Where(i => i != 0).ToArray();
if (nonZeros.Length < 1)
{
return;
}
else
{
foreach (byte b in bytes)
handler.handleByteReceived((char)b);
}
}
else if (uuid == UUID_MODE)
{
//
}
}
};
selectedPeripheral.DiscoveredService += (sender, e) =>
{
var services = selectedPeripheral.Services;
if (services != null)
{
foreach (CBService service in services)
{
if (service.UUID.ToString(true).ToLower() == UUID_TRUCONNECT)
{
truConnect = service;
selectedPeripheral.DiscoverCharacteristics(truConnect);
}
}
}
};
selectedPeripheral.DiscoveredCharacteristic += (sender, e) =>
{
if (truConnect != null && truConnect.Characteristics != null)
{
foreach (CBCharacteristic c in truConnect.Characteristics)
{
var uuidString = c.UUID.ToString(true).ToLower();
if (uuidString == UUID_RX)
{
rx = c;
}
else if (uuidString == UUID_TX)
{
tx = c;
}
else if (uuidString == UUID_MODE)
{
mode = c;
// set to stream mode
selectedPeripheral.WriteValue(NSData.FromArray(new byte[] { MODE_COMMAND }), mode, CBCharacteristicWriteType.WithResponse);
}
}
}
};
selectedPeripheral.WroteCharacteristicValue += (sender, e) =>
{
// if UUID is for RX, we just wrote to RX. Drill down to
// TX characteristic and read it. This will trigger
// the UpdatedCharacteristicValue event.
string uuid = e.Characteristic.UUID.ToString(true).ToLower();
if (uuid == UUID_RX)
{
var services = selectedPeripheral.Services;
if (services != null)
{
foreach (CBService s in services)
{
if (s.UUID.ToString(true).ToLower() == UUID_TRUCONNECT)
{
var charachteristics = s.Characteristics;
if (charachteristics != null && charachteristics.Length > 0)
{
foreach (CBCharacteristic c in charachteristics)
{
if (c.UUID.ToString(true).ToLower() == UUID_TX)
{
Timer t = new Timer(new TimerCallback(delegate(object o)
{
selectedPeripheral.ReadValue(c);
}), null, TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(-1));
}
}
}
}
}
}
}
};
manager.ConnectPeripheral(selectedPeripheral);
}
Writes to rx. This is what should be used to actually send commands.
public void sendCommand(string command)
{
command += endString + "\n";
if (rx != null)
{
NSData d = NSData.FromString(command);
foreach (CBService s in selectedPeripheral.Services)
{
if (s.UUID.ToString(true).ToLower() == UUID_TRUCONNECT)
foreach (CBCharacteristic c in s.Characteristics)
{
if (c.UUID.ToString(true).ToLower() == UUID_RX)
selectedPeripheral.WriteValue(NSData.FromString(command), c, CBCharacteristicWriteType.WithResponse);
}
}
}
}
So my question is, why am I not getting the expected data when the CBPeripheral.UpdatedCharacteristicValue event is called? Occasionally I will get the expected data, but it is quite rare, and I can't seem to find any logical reason or pattern that would explain why this is happening.
AHA! I figured it out!
The problem was that I need to set the notify value for the appropriate characteristics. After doing that, I didn't need to call CBPeripheral.ReadValue(CBCharacteristic).
selectedPeripheral.DiscoveredCharacteristic += (sender, e) =>
{
if (truConnect != null && truConnect.Characteristics != null)
{
foreach (CBCharacteristic c in truConnect.Characteristics)
{
var uuidString = c.UUID.ToString(true).ToLower();
if (uuidString == UUID_RX)
{
rx = c;
}
else if (uuidString == UUID_TX)
{
tx = c;
// set the notify value to true and poof!
// now CBPeripheral.UpdatedCharacteristicValue
// event will be triggered at the appropriate time.
selectedPeripheral.SetNotifyValue(true, tx);
}
else if (uuidString == UUID_MODE)
{
mode = c;
// set to remote command mode
selectedPeripheral.WriteValue(NSData.FromArray(new byte[] { MODE_COMMAND }), mode, CBCharacteristicWriteType.WithResponse);
}
}
}
};

Set an OnClickListener for an SVG element

Say I have an SVG element, as follows. How do I add an onClickListener?
solved, see below.
I'm going to guess you're meaning a FieldChangeListener rather than an OnClickListener (wrong platform ;). SVGImage isn't part of the RIM-developed objects, so unfortunately you won't be able to. Anything that is going to be able to have a FieldChangeListner has to be a subclass of the net.rim.device.api.ui.Field class.
Just in case someone's interested in how it's done...
try {
InputStream inputStream = getClass().getResourceAsStream("/svg/sphere1.svg");
_image = (SVGImage)SVGImage.createImage(inputStream, null);
_animator = SVGAnimator.createAnimator(_image, "net.rim.device.api.ui.Field");
_document = _image.getDocument();
_svg123 = (SVGElement)_document.getElementById("123");
}
catch (IOException e) { e.printStackTrace(); }
Field _svgField = (Field)_animator.getTargetComponent();
_svgField.setBackground(blackBackground);
add(_svgField);
_svg123.addEventListener("click", this, false);
_svg123.addEventListener("DOMFocusIn", this, false);
_svg123.addEventListener("DOMFocusOut", this, false);
}
public void handleEvent(Event evt) {
if( _svg123 == evt.getCurrentTarget() && evt.getType() == "click" ){ Dialog.alert("You clicked 123"); }
if( _svg123 == evt.getCurrentTarget() && evt.getType() == "DOMFocusIn" ) { ((SVGElement) _document.getElementById("outStroke123")).setTrait("fill", "#FF0000"); }
if( _svg123 == evt.getCurrentTarget() && evt.getType() == "DOMFocusOut" ) { ((SVGElement) _document.getElementById("outStroke123")).setTrait("fill", "#2F4F75"); }
}

open shazam from my blackberry application

I need the code open shazam(other intalled applications in the phone) if its installed.
How can I check whether shazam is installed in a phone,and if installed how can I open it from my app?If any one have idea please help.Thanks in advace.
public static ApplicationDescriptor getApplicationDescriptor(String appName) {
try {
int[] moduleHandles = CodeModuleManager.getModuleHandles();
if (moduleHandles != null && moduleHandles.length > 0) {
for (int i = 0; i < moduleHandles.length; i++) {
ApplicationDescriptor[] applicationDescriptors = CodeModuleManager.getApplicationDescriptors(moduleHandles[i]);
if (applicationDescriptors != null && applicationDescriptors.length > 0) {
for (int j = 0; j < applicationDescriptors.length; j++) {
if (applicationDescriptors[j].getModuleName().toLowerCase().equals(appName.toLowerCase())) {
return applicationDescriptors[j];
}
}
}
}
}
} catch (Exception e) {
System.out.println("error at getApplicationDescriptor" + e);
}
return null;
}
public static int runApplication(String appName) {
int processId = -1;
ApplicationDescriptor appDescriptor = getApplicationDescriptor(appName);
if (appDescriptor != null) {
//is not null Application installed
processId = ApplicationManager.getApplicationManager().getProcessId(appDescriptor);
if (processId == -1) {
// -1 if application has no process (i.e. is not running).
try {
processId = ApplicationManager.getApplicationManager().runApplication(appDescriptor);
} catch (ApplicationManagerException e) {
e.printStackTrace();
}
}
}
return processId;
}
call runApplication like
int pid=-1;
if((pid=runApplication(appName))>-1){
//application running
System.out.println(appName +" runing with process id "+pid);
}

Resources