HOw to pair the bluetooth in two devices using NFC - bluetooth

I am trying to pair two devices
One is Google Nexus S which has the applicaion running which reads the mac address written over the tag which is stuck on the other phone which is not Android one .
Now i am trying to pair the devices as i tap on the other phone , my application reads the MAC address stored in the TAG and automatically creates the Bluetooth connection .
Everything is working fine but i am getting a pairing request or to match the keys on both the phones which should not come.
Here is the Bluetooth Segment where the connection is happening
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private String mSocketType;
public ConnectThread(BluetoothDevice device, boolean secure) {
mmDevice = device;
BluetoothSocket tmp = null;
mSocketType = secure ? "Secure" : "Insecure";
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
if (secure) {
tmp = device.createRfcommSocketToServiceRecord(
MY_UUID_SECURE);
} else {
tmp = device.createInsecureRfcommSocketToServiceRecord(
MY_UUID_INSECURE);
Log.d("CHECK", "Sucessfully created insecure socket");
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
}
mmSocket = tmp;
}
public void run() {
Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType);
setName("ConnectThread" + mSocketType);
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
Log.d("CHECK", "Inside RUN");
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
Log.d("CHECK", "Trying to connect");
mmSocket.connect();
Log.d("CHECK", "Tried to connect");
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
Log.d("CHECK", "Socket closed");
} catch (IOException e2) {
Log.e(TAG, "unable to close() " + mSocketType +
" socket during connection failure", e2);
}
Log.d("CHECK", "Connection failed");
connectionFailed();
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothChatService.this) {
mConnectThread = null;
}
// Start the connected thread
connected(mmSocket, mmDevice, mSocketType);
Log.d("CHECK RESULT", "Sucessfully connected");
// Toast.makeText(BluetoothChatService.ConnectThread.this, "Sucessfully connected" , Toast.LENGTH_LONG).show();
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e);
}
}
}
I am trying for the insecure connection , but i dont know why it is asking for the pairing keys in both the phones.

Chek your bluetooth version because:
(sic) "For Bluetooth 2.1 devices, the link key will be encrypted, as encryption is mandatory. For legacy devices (pre Bluetooth 2.1 devices) the link key will be not be encrypted."

Related

My app crashes when I try to send a request to the server

Well, it actually works pretty well on my android studio simulator but when I try to run it on my phone it just crashes.
I just want to send a number to the server and get a response with the data that I need to that number. so this is my code which do that:
thread = new Thread() {
#Override
public void run() {
//server stuff
try {
//Connecting
if(!userClass.equals("")) {
Log.i(debugString, "Attempting to connect to server");
socket = new Socket(hostname, portnumber);
Log.i(debugString, "Connection established!");
BufferedWriter bw = new BufferedWriter((new OutputStreamWriter(socket.getOutputStream())));
bw.write("" + userClass);
bw.newLine();
bw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
input = br.readLine();
}
} catch (IOException e) {
Log.e(debugString, e.getMessage());
} finally {
threadComplete = true;
}
}
};
thread.start();
while(!threadComplete)
continue;
then I just use this thread whenever I want to get the updated info for my request like that:
String getUserClass = userClass;
if(!getUserClass.equals(""))
{
threadComplete = false;
userClass = getUserClass;
thread.start();
while (!threadComplete)
continue;
changes.setText(input);
}
else Toast.makeText(this, "Error, choose your class", Toast.LENGTH_SHORT).show();
BTW, in the end of every thread (on the emulator because on my phone it crashes) I get a message:
Skipped 91 frames! The application may be doing too much work on its main thread.
and I have another problem, I also use IntentService to run my app service on the background, and obviously I don't want it to run constantly forever, so I made a loop which contains at the end of each loop a wait() command, but the problem is that when I set the time to wait for longer than 3000 milliseconds or so, the service crashes.
my code for the background service:
synchronized (this) {
int count = 0;
while (count<4) {
try {
wait(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (notifications && !userClass.equals("")) {
new Thread() {
#Override
public void run() {
//server stuff
try {
//Connecting
if (!userClass.equals("")) {
Log.i("debug", "Attempting to connect to server");
socket = new Socket(hostname, portnumber);
Log.i("debug", "Connection established!");
BufferedWriter bw = new BufferedWriter((new OutputStreamWriter(socket.getOutputStream())));
bw.write("" + userClass);
bw.newLine();
bw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
input = br.readLine();
}
} catch (IOException e) {
Log.e("debug", e.getMessage());
} finally {
complete = true;
}
}
}.start();
while (!complete)
continue;
Toast.makeText(this, "" + input, Toast.LENGTH_SHORT).show();
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.chanka)
.setContentTitle("ביטול שיעורים: ")
.setContentText(input);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
mNotificationId++;
Toast.makeText(this, "" + input, Toast.LENGTH_SHORT).show();
count++;
}
}
}
This following piece of code is the culprit -
while (!threadComplete)
continue;
You are kind of putting the main thread on a long loop. Android does not allow that. The general construct in these kind of use cases is this -
Step 1 - Show a progress dialog to the user indicating that you are
doing something important and user needs to wait till that is
complete. Show some meaningful text in the progress dialog which makes
sense to the user.
Step 2 - Start a async connection to the server. There are lot of
options in Android to do this. But for your purpose AsyncTask might
be useful. Connect to your server, fetch and parse data in the
doInBackground method of AsyncTask and once the task is complete,
let onPostExecute publish the same to the Main thread.
Step 3 - Once you get back the result from the Async task, you may
dismiss the progress dialog and continue with whatever you were doing.
Please note that the main thread should not be blocked at any time. This is the event handling thread of the app and handles all events (User initiated or system initiated). If the thread is blocked, you get the kind of error you are seeing now. Specifically in your case, Android system is not able to do some draw operations because of the while loop.
Create a new Asynctask and run the socket establisment codes inside it :)
socket = new Socket(hostname, portnumber);

RFCommConnectionTrigger in Windows Universal Apps To detect Incoming Bluetooth Connection

I am working on a Windows Universal App. I Want to get the Data from a Bluetooth Device to the Windows Phone. I am Using the Concept of RFCommCommunicationTrigger for this Purpose.
Here's the code Snippet I am Using
var rfTrigger = new RfcommConnectionTrigger();
// Specify what the service ID is
rfTrigger.InboundConnection.LocalServiceId = RfcommServiceId.FromUuid(new Guid("<some_base_guid>"));
//Register RFComm trigger
var rfReg = RegisterTaskOnce(
"HWRFCommTrigger",
"BackgroundLibrary.RFBackgroundTask",
rfTrigger, null
);
SetCompletedOnce(rfReg, OnTaskCompleted);
Here the Function of RegisterTaskOnce
static private IBackgroundTaskRegistration RegisterTaskOnce(string taskName, string entryPoint, IBackgroundTrigger trigger, params IBackgroundCondition[] conditions)
{
// Validate
if (string.IsNullOrEmpty(taskName)) throw new ArgumentException("taskName");
if (string.IsNullOrEmpty(entryPoint)) throw new ArgumentException("entryPoint");
if (trigger == null) throw new ArgumentNullException("trigger");
// Look to see if the name is already registered
var existingReg = (from reg in BackgroundTaskRegistration.AllTasks
where reg.Value.Name == taskName
select reg.Value).FirstOrDefault();
Debug.WriteLine("Background task "+ taskName+" is already running in the Background");
// If already registered, just return the existing registration
if (existingReg != null)
{
return existingReg;
}
// Create the builder
var builder = new BackgroundTaskBuilder();
builder.TaskEntryPoint = entryPoint;
builder.Name = taskName;
builder.SetTrigger(trigger);
// Conditions?
if (conditions != null)
{
foreach (var condition in conditions)
{
builder.AddCondition(condition);
}
}
// Register
return builder.Register();
}
Here's the code for SetCompletedOnce this will add a Handler only once
static private void SetCompletedOnce(IBackgroundTaskRegistration reg, BackgroundTaskCompletedEventHandler handler)
{
// Validate
if (reg == null) throw new ArgumentNullException("reg");
if (handler == null) throw new ArgumentNullException("handler");
// Unsubscribe in case already subscribed
reg.Completed -= handler;
// Subscribe
reg.Completed += handler;
}
I have also Written the BackgroundLibrary.RFBackgroundTask.cs
public sealed class RFBackgroundTask : IBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
try
{
Debug.WriteLine(taskInstance.TriggerDetails.GetType());
taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
Debug.WriteLine("RFComm Task Running");
Debug.WriteLine(taskInstance.TriggerDetails.GetType().ToString());
}
catch (System.Exception e)
{
Debug.WriteLine("RFComm Task Error: {0}", e.Message);
}
deferral.Complete();
}
}
The Run Method is Invoked Every Time The Device tries to Open the Connection.
The type of the Trigger that is obtained (the type I am debugging in the run method of the RFBackgroundTask.cs) is printed as
Windows.Devices.Bluetooth.Background.RfcommConnectionTriggerDetails
But I am Unable use that because I dont have this Class in the BackgroundLibrary project.
The Documentation says that this Provides information about the Bluetooth device that caused this trigger to fire.
It has Variables like Socket,RemoteDevice etc.
I think I am Missing something very simple
Can you please help me out .
Once your background task is launched, simply cast the TriggerDetails object to an RfcommConnectionTriggerDetails object:
public sealed class RFBackgroundTask : IBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
try
{
taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
RfcommConnectionTriggerDetails details = (RfcommConnectionTriggerDetails)taskInstance.TriggerDetails;
StreamSocket = details.Socket; // Rfcomm Socket
// Access other properties...
}
catch (System.Exception e)
{
Debug.WriteLine("RFComm Task Error: {0}", e.Message);
}
deferral.Complete();
}
}

how to check if device is registered for windows phone push notification

I am using notification hub to register my windows phone device for push notification service.Once if I register my device and again if I register my device for push notification I am getting two notifications means a single device is registering for two time.Can anyone please tell me how to prevent a user to register for more than once.
My code is as:
public static async Task SetupPushNotifications()
{
await RegisterWithNotificationHub();
}
private static HttpNotificationChannel CreateHttpNotificationChannel(string channelName)
{
var httpChannel = HttpNotificationChannel.Find(channelName);
#endregion
return httpChannel;
}
private static async Task RegisterWithNotificationHub()
{
try
{
// requesting a channel from MPNS
App.NotificationChannel = CreateHttpNotificationChannel("");
App.ClientHub = new NotificationHub(
"",""
);
var storedTagsForUser = await GetRegistrationsTagsFromBackEnd();
await RegisterTemplateNotificationWithNotificationHub(storedTagsForUser);
}
catch (Exception exc)
{
Debug.WriteLine(exc);
}
}
private static async Task RegisterTemplateNotificationWithNotificationHub(IEnumerable<string> tags)
{
var toastMessageTemplate =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>$(oppTitleValue)</wp:Text1>" +
"<wp:Text2>$(myToastMessage)</wp:Text2>" +
"<wp:Param>$(pageToOpen)</wp:Param>" +
"</wp:Toast>" +
"</wp:Notification>";
try
{
await App.ClientHub.RegisterTemplateAsync(
App.NotificationChannel.ChannelUri.AbsoluteUri,
xmlTemplate: toastMessageTemplate,
templateName: TemplateRegistrationName,
tags: tags);
}
catch (Exception exc)
{
Debug.WriteLine("Error registering template notification with notification hubs: " + exc);
}
}
You can check if the channel already exists by calling HttpNotificationChannel.Find(channelName). It will return null if it doesn't.
So you would only want to create a channel if it doesnt't already exist. For example
private void RegisterPushChannel()
{
HttpNotificationChannel currentChannel = HttpNotificationChannel.Find("MyPushChannel");
if (currentChannel == null)
{
currentChannel = new HttpNotificationChannel("MyPushChannel");
currentChannel.Open();
currentChannel.BindToShellTile();
currentChannel.BindToShellToast();
}
}

PushSharp for APNS works on local server but not on azure

I am using push sharp in a ASP.NET web api server. on my local computer everything works like a charm for GCM and APNS but once uploaded to azure only the GCM messages work. the APNS is not working, not throwing exceptions nothing. I have traces in every event the push broker throws but no trace message is called. not even the message queued...
Here is my initialization code:
public PushNotificationManager()
{
_pushService = new PushBroker();
_pushService.OnChannelCreated += OnChannelCreated;
_pushService.OnChannelDestroyed += OnChannelDestroyed;
_pushService.OnChannelException += OnChannelException;
_pushService.OnDeviceSubscriptionChanged += OnDeciveSubscriptionChanged;
_pushService.OnDeviceSubscriptionExpired += OnDeviceSubscriptionExpired;
_pushService.OnNotificationFailed += OnNorificationFailed;
_pushService.OnNotificationRequeue += OnNotificationQueued;
_pushService.OnNotificationSent += OnNOtificationSend;
_pushService.OnServiceException += OnServiceException;
InitAndroidPushService();
InitApplePushService();
}
private void InitApplePushService()
{
try
{
string appDataPath = HttpContext.Current.Server.MapPath("~/app_data");
//***** Development Server *****//
//string file = Path.Combine(appDataPath, "PushSharp.PushCert.Development.p12");
//var appleCert = File.ReadAllBytes(file);
// _applePushService = new ApplePushService(new ApplePushChannelSettings(false, appleCert, "XXXXXXX"));
//***** Production Server *****//
string file = Path.Combine(appDataPath, "PushSharp.PushCert.Production.p12");
var appleCert = File.ReadAllBytes(file);
_pushService.RegisterAppleService(new ApplePushChannelSettings(true, appleCert, "XXXXXX"));
Trace.TraceInformation("ApplePushService initialized succesfully");
}
catch (Exception e)
{
Trace.TraceError("Error initializing ApplePushService : " + e);
throw;
}
}
private void InitAndroidPushService()
{
try
{
_pushService.RegisterGcmService(new GcmPushChannelSettings("XXXXXX", "XXXXXX",
"XXXXX"));
Trace.TraceInformation("GooglePushService initialized succesfully");
}
catch (Exception e)
{
Trace.TraceError("Error initializing AndroidPushService : " + e);
}
}
Has anyone enountered such a thing?

Sending email from Blackberry java development

I have a question with sending email from Blackberry java development.
My application sends mail correctly, but it defaults in FROM the previously configured mail on the BlackBerry device, I don't know how to replace the header FROM for another email diferent like the email configured in the Blackberry device, I put my code below:
try {
Address() ad = new Address ("emailexample#hotmail.com", "Maria Gomez");
} Catch (AddressException e) {
try {
Store store = Session.getDefaultInstance().getStore ();
Folder [] folders = store.list (Folder.SENT);
Sentfolder folder = folders [0];
msg = new Message (sentfolder);
try {
String [] v = splitString (toField.getText (), ',', false);
toList = new Address [v.length];
for (int i = 0; i <v.length i + +)
{
toList [i] = new Address (v [i], "");
}
} Catch (AddressException e) {System.out.println (e.toString ());}
msg.addRecipients (Message.RecipientType.TO, toList);
msg.setSubject (subjectField.getText ());
msg.setContent (msgField.getText ());
msg.setFrom (ad);
if (toField.getText().compareTo("") == 0 | | fromField.getText().compareTo("")==0)
{
Dialog.alert ("ERROR: \ n Lack mail recipient \ no sender");
}
else
{
Transport.send (msg);
Dialog.alert ("the mail was sent");
subjectField.setText ("");
msgField.setText ("");
}
} Catch (MessagingException e) {
System.out.println (e.getMessage ());
Dialog.alert ("No mail was sent");
}
I try to use msg.setFrom (ad), but dosen't work, then i try using msg.setHeader ("FROM", "emailexample#gmail.com") an neither work.
Waiting for helps, Thanks.
hi try this it work fine,,
public void TextMailSend()
{
String htmlContent = " Name:"+Name+ "\n Common Name:"+cmn_nm +"\n Radious:"+radius+"\n Year:"+yr+"\n Latitude:"+lat +"\n Longitude :"+lng ;
Message msg = new Message();
try
{
final Address address = new Address("","");
Address[] addresses = {address};
msg.addRecipients(net.rim.blackberry.api.mail.Message.RecipientType.TO, addresses);
msg.setContent(htmlContent);
msg.setSubject("Subject");
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments(msg));
//Dialog.inform("Mail send fully.");
}
catch (AddressException e)
{
e.printStackTrace();
System.out.println("AddressException -->"+e.getMessage());
}
catch (MessagingException e)
{
e.printStackTrace();
System.out.println("MessagingException -->"+e.getMessage());
}
}

Resources