Midlet crashes when calling bluetooth API - java-me

When I run following code on my phone I get black screen saying there was uncaught exception but whole block is wrapped in try/catch block so it is weird, anyway when I proceed with execution code just gets to "Getting device.." so it obviously fails on this line:
LocalDevice local = LocalDevice.getLocalDevice();
Here is whole method:
public void startBT()
{
try
{
f.append("Getting device..");
LocalDevice local = LocalDevice.getLocalDevice();
f.append("Got local device..");
DiscoveryAgent agent = local.getDiscoveryAgent();
f.append("Got local discovery agent..");
connString = agent.selectService(new UUID(
"86b4d249fb8844d6a756ec265dd1f6a3", false),
ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
f.append("Got connection string - >" + connString);
}
catch (Exception ex)
{
Alert message = new Alert("info");
message.setString(ex.getMessage());
Display.getDisplay(this).setCurrent(message);
}
}
Any ideas?

It looks like device I used doesn't support JSR-82 which is J2ME Bluetooth API(this is built into phone, no way of "installing" it) required to use Bluetooth from J2ME Midlets,here is snippet which should check for JSR-82 support:
public static boolean IsBtJsrComaptible() {
try {
Class.forName("javax.bluetooth.LocalDevice");
return true;
} catch (Exception e) {
return false;
}
}
Please note that I got uncaught exception trying to run above snippet, but maybe it would work on some other device.

Related

xamarin ios app crashing with CBCentralManager

I have a Fresh application with basically no code added to it except the following Code.
If I try it in a simulator it goes into update state and says unsupported.
If I try to run in on a 6 generation ipad (with bluetooth turned on) the application crashes as soon as debugging exits UIButton231_TouchUpInside (and never goes into the catch).
Am I missing anything?
CBCentralManager _central;
partial void UIButton231_TouchUpInside(UIButton sender)
{
try
{
BluetoothLEManager();
}
catch (Exception e)
{
Console.Write(e);
}
}
protected void BluetoothLEManager()
{
try
{
_central = new CBCentralManager(DispatchQueue.CurrentQueue);
_central.DiscoveredPeripheral += (object sender, CBDiscoveredPeripheralEventArgs e) =>
{
Console.WriteLine("DiscoveredPeripheral: " + e.Peripheral.Name);
Console.WriteLine("RSSI: " + e.Peripheral.RSSI);
};
_central.UpdatedState += (object sender, EventArgs e) =>
{
Console.WriteLine("UpdatedState: " + _central.State);
};
_central.ConnectedPeripheral += (object sender, CBPeripheralEventArgs e) =>
{
Console.WriteLine("ConnectedPeripheral: " + e.Peripheral.Name);
};
_central.DisconnectedPeripheral += (object sender, CBPeripheralErrorEventArgs e) =>
{
Console.WriteLine("DisconnectedPeripheral: " + e.Peripheral.Name);
};
}
catch (Exception e)
{
Console.Write(e);
}
}
In the Image below (code is compacted to make the image shorter), debugging reaches line 62 just fine, but attempting to step over or to just let it continue will close the application, and breakpoints in the catch are not reached.
I have tried shared code in local site , and it also crashes and with some error logs :
After checking this line error :
Got a SIGABRT while executing native code. This usually indicates a fatal error in the mono runtime or one of the native libraries used by your application.
Sometimes that may be caused by permission in iOS . You can have a look at this aticle by James : New iOS 10 Privacy Permission Settings .
Starting in iOS 10, nearly all APIs that require requesting authorization and other APIs, such as opening the camera or photo gallery, require a new key value pair to describe their usage in the Info.plist.
However , in info.plist , you can add the permission of Bluetooth easily as follow and will forget another most important permission :
<key>NSBluetoothPeripheralUsageDescription</key>
<string>Add BlueTooth Peripheral Permission</string>
That's not enough for Bluetooth . You also need to add another permission :
<key>NSBluetoothAlwaysUsageDescription</key>
<string>use Bluetooth</string>
From native info.plist , you also will find it .
This permission is fundamental and necessary . Because this will pop up a permission Dialog window in iOS device .
By the way , there is an offical API about using Bluetooth in Xamarin iOS you can have a look .
public class MySimpleCBCentralManagerDelegate : CBCentralManagerDelegate
{
override public void UpdatedState (CBCentralManager mgr)
{
if (mgr.State == CBCentralManagerState.PoweredOn) {
//Passing in null scans for all peripherals. Peripherals can be targeted by using CBUIIDs
CBUUID[] cbuuids = null;
mgr.ScanForPeripherals (cbuuids); //Initiates async calls of DiscoveredPeripheral
//Timeout after 30 seconds
var timer = new Timer (30 * 1000);
timer.Elapsed += (sender, e) => mgr.StopScan();
} else {
//Invalid state -- Bluetooth powered down, unavailable, etc.
System.Console.WriteLine ("Bluetooth is not available");
}
}
public override void DiscoveredPeripheral (CBCentralManager central, CBPeripheral peripheral, NSDictionary advertisementData, NSNumber RSSI)
{
Console.WriteLine ("Discovered {0}, data {1}, RSSI {2}", peripheral.Name, advertisementData, RSSI);
}
}
public partial class HelloBluetoothCSharpViewController : UIViewController
{
MySimpleCBCentralManagerDelegate myDel;
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
//Important to retain reference, else will be GC'ed
myDel = new MySimpleCBCentralManagerDelegate ();
var myMgr = new CBCentralManager (myDel, DispatchQueue.CurrentQueue);
}

Error while processing request in AzureMobile Apps HTTP2 error

This question is specific to a lately strange behavior of the Azure mobile Apps Android sdk. Everything was working fine for weeks. Now, my android client app suddenly can't connect to my web app any more. A Toast says "Error while processing request". In Android Studio debugger, I found the exception inside the SDK file MobileServiceConnection.java.
java.io.IOException: stream was reset: PROTOCOL_ERROR
In Azure Portal, my app shows "Healthy" status, but I can see the HTTP errors. Please help.
Following is my code, which was working fine and now throws error.
// Create the Mobile Service Client instance, using the provided mobile app URL.
try {
mClient = new MobileServiceClient(mMobileBackendUrl, activityContext).withFilter(
new ServiceFilter() {
#Override
public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request, NextServiceFilterCallback nextServiceFilter) {
// Get the request contents
String url = request.getUrl();
String content = request.getContent();
if (url != null) {
Log.d("Request URL:", url);
}
if (content != null) {
Log.d("Request Content:", content);
}
// Execute the next service filter in the chain
ListenableFuture<ServiceFilterResponse> responseFuture = nextServiceFilter.onNext(request);
Futures.addCallback(responseFuture, new FutureCallback<ServiceFilterResponse>() {
#Override
public void onFailure(Throwable exception) {
Log.d("Exception:", exception.getMessage());
}
#Override
public void onSuccess(ServiceFilterResponse response) {
if (response != null && response.getContent() != null) {
Log.d("Response Content:", response.getContent());
}
}
});
return responseFuture;
}
}
);
setAzureClient(mClient);
}catch(MalformedURLException e){
createAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
}catch(Exception e){
createAndShowDialog("There was an error creating the Mobile Service. "+ e.toString(), "Error");
}
Toast.makeText(context, context.getString(R.string.online_authentication), Toast.LENGTH_SHORT).show();
authenticate();
}
private void authenticate() { // give access only to authenticated users via Google account authentication
HashMap<String, String> parameters = new HashMap<>();
parameters.put("access_type", "offline");//use "Refresh tokens"
//login with the Google provider. This will create a call to onActivityResult() method inside the context Activity, which will then call the onActivityResult() below.
mClient.login(MobileServiceAuthenticationProvider.Google, url_scheme_of_your_app, GOOGLE_LOGIN_REQUEST_CODE, parameters);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// When request completes
if (requestCode == 1) {
try {
MobileServiceActivityResult result = mClient.onActivityResult(data);
if (result.isLoggedIn()) {
Toast.makeText(context, context.getString(R.string.azure_auth_login_success) /*+ " " + mClient.getCurrentUser().getUserId()*/, Toast.LENGTH_SHORT).show();
mUserId = mClient.getCurrentUser().getUserId();
} else {//>>>>THIS IS WHERE I AM GETTING THE ERROR
String errorMessage = result.getErrorMessage();
Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show();// Error While processing request (it comes form the MobileServiceConnection.java file inside sdk)
}
}catch(Exception e){
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
I found the answer myself. The error was due to an Azure App Service HTTP2 connection issue. It has nothing to do with the app code. For anyone facing the same problem, here is the solution.
Go to https://resources.azure.com/
Make sure you are in Read/Write mode by clicking in the option to the left of your name.
From the left column, browse to: https://resources.azure.com/subscriptions/yourSubscriptionId/resourceGroups/yourWebAppResourceGroup/providers/Microsoft.Web/sites/yourWebAppName/config/web
Find and Change the property: "http20Enabled": from true to false by clicking EDIT, Update value to “false” and then clicking in Save or PATCH.

Android Studio - Cannot Connect to Bluetooth Device

Well, I have everything set up to create a connection to another bluetooth device.
I have a ListView that shows me devices that are paired to my bluetooth device and when I click on the desired device within the listView it should connect to it, but somehow the connection is not being established.
Here is a sample of my paired devices List:
public void getPairedDevices(){
pairedDevices = myBluetoothAdapter.getBondedDevices();
pairedDevices_ArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1);
if(pairedDevices.size()>0){
for(BluetoothDevice device : pairedDevices){
pairedDevices_ArrayAdapter.add(device.getName()+"\n"+device.getAddress());
}
}
pairedDevices_ListView.setAdapter(pairedDevices_ArrayAdapter);
pairedDevices_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String i = ((TextView) view).getText().toString();
String address = i.substring(i.length() - 17);
deviceToConnectTo = myBluetoothAdapter.getRemoteDevice(address);
connectToDevice(deviceToConnectTo);
}
});
}
And here is my connectToDevice() void:
public void connectToDevice(BluetoothDevice device){
try {
mmSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
myBluetoothAdapter.cancelDiscovery();
} catch (IOException e){}
try{
mmSocket.connect();
} catch (IOException e){
showMsg("Error Connecting to device");
try{
mmSocket.close();
} catch (IOException exception){}
}
}
showMsg is basically a Toast.makeText, it keeps giving me "
Error Connecting to device
toast message, which means that somehow it was impossible to connect.
Can someone tell me why?
I'm using API level 10 and trying to connect to HC-05 Bluetooth Module.
Ok, it seems I managed to fix the problem of not connecting to the HC-05 Bluetooth module. The problem was the UUID I was using.
I changed the UUID to:
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
It's used to bluetooth serial boards such as HC-05.

Failed to connect [10048]

I've got this code on a button, when I press it I get the Error:
Error: Exception connecting to NXT.
Caused by lejos.pc.comm.NXTCommException: Open of NXT failed.
at lejos.pc.comm.NXTCommBluecove.open(NXTCommBluecove.java:136)
Caused by javax.bluetooth.BluetoothConnectionException: Failed to connect; [10048]
Only one usage of each socket address (protocol/network address/port) is normally permitted.
at com.intel.bluetooth.BluetoothStackMicrosoft.connect(Native Method)
Failed to connect to any NXT
I am posting because it was working fine yesterday but seems not to be working today.
btnConnectBot.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (Cnt1){
try {
conn.close();
Cnt1=!Cnt1;
txtConnState.setText("Off");
txtConnState.setForeground(Color.RED);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else{
conn.addLogListener(new NXTCommLogListener() {
public void logEvent(String message) {
System.out.println(message);
}
public void logEvent(Throwable throwable) {
System.err.println(throwable.getMessage());
}
});
conn.setDebug(true);
if (!conn.connectTo(txtBotName.getText(), NXTComm.LCP)) {
System.err.println("Fallo de conexión");
txtConnState.setText("Off");
txtConnState.setForeground(Color.RED);
System.exit(1);
}
Cnt1=!Cnt1;
txtConnState.setText("On");
txtConnState.setForeground(Color.GREEN);
if (chckbxLock_2.isSelected()){
btnConnectBot_2.doClick();
}
if (chckbxLock_1.isSelected()){
btnConnectBot_1.doClick();
}
}
}
});
According to my research this is because the bluetooth port being used is being accessed by more than one instance. But I don't see how this happens in this code.
Do you have a Bluetooth virtual COM port configured for the remote device? Maybe it is opened by some program...
Or, does the error occur the first time you run your program? Are there any old copies of your program running -- check in taskmgr.exe

Unable to open camera on samsung phone in j2me

I have written following piece of code. It is used to create camera player. I tested it on nokia phones. It's working fine and I am able to see camera and use its functionality.
But the issue is that when the code is tested on samsung phone it throws Media exception and eventually have to make an exit from the application. Due to this code, my inbuilt camera functionality (i.e. on samsung phone) also stops working. So what's the reason to it?
public void startCamera()
{
try
{
try
{
// if player==null
player = createPlayer();
}
catch (Exception ex)
{
ex.printStackTrace();
ErrorDialog.show(ex, "We are exiting the application.",
"Exit", new com.auric.qrev.scanqrcode.lwuit.ui.Action(){
public void actionPerformed() {
m_objMIDlet.exitApp();
}
});
}
try
{
player.realize();
player.prefetch();
}
catch (MediaException ex)
{
ex.printStackTrace();
ErrorDialog.show(ex, "We are exiting the application.",
"Exit", new com.auric.qrev.scanqrcode.lwuit.ui.Action(){
public void actionPerformed() {
m_objMIDlet.exitApp();
}
});
}
//Grab the video control and set it to the current display.
videoControl = (VideoControl)(player.getControl("VideoControl"));
if (videoControl == null)
{
//discardPlayer();
stopCamera();
ErrorDialog.show("Unsupported:\n"+
"Can't get video control\n"+
"We are exiting the application.",
"Exit", new com.auric.qrev.scanqrcode.lwuit.ui.Action(){
public void actionPerformed() {
m_objMIDlet.exitApp();
}
});
}
mediaComponent = new MediaComponent(player);
mediaComponent.setFocusable(false);
m_cameraScreen.showCamera(mediaComponent);
start();
}
catch(Exception ex)
{
ex.printStackTrace();
//discardPlayer();
stopCamera();
ErrorDialog.show("Sorry,Resources unavailable.\nWe are exiting the application.",
"Exit", new com.auric.qrev.scanqrcode.lwuit.ui.Action(){
public void actionPerformed() {
m_objMIDlet.exitApp();
}
});
}
}
private Player createPlayer()throws MediaException, Exception
{
Player mPlayer = null;
// try capture://image first for series 40 phones
try
{
mPlayer = Manager.createPlayer("capture://image");
}
catch (Exception e)
{
e.printStackTrace();
}
catch (Error e)
{
e.printStackTrace();
}
// if capture://image failed, try capture://video
if (mPlayer == null)
{
try
{
mPlayer = Manager.createPlayer("capture://video");
}
catch (Exception e)
{
e.printStackTrace();
throw new MediaException("Sorry,Resources unavailable.");
}
}
if(mPlayer == null)
throw new Exception("Sorry,Resources unavailable.");
return mPlayer;
}
First things first, you have to realize that printStackTrace() is pretty much useless outside of the emulator unless you are using a Symbian phone.
You can also use java.lang.Throwable instead of separating Exception and Error
You can figure out exactly what happens by gathering information as a String and appending it to a simple lcdui Form while you are testing:
try {
// do something that could potentially fail
} catch (Throwable th) {
myDebugLcduiForm.append("potential failure number xx." + th + th.getMessage());
// if necessary, throw a new RuntimeException
}
You might want to update/repost your question once you know exactly what line of code throws what exception.

Resources