What actually does system method removeBond() in Android? - bluetooth-lowenergy

I know, this method removes ble device/tag from list of bonded devices in android smartphone. But maybe he have other hidden functions, for example: send some commands to remove bond in ble device/tag side ?
How i can call method in android:
try {
Method method = device.getClass().getMethod("removeBond", (Class[]) null);
result = (boolean) method.invoke(device, (Object[]) null);
if (result) {
Log.i(TAG, "Successfully removed bond");
}
return result;
} catch (Exception e) {
Log.e(TAG, "ERROR: could not remove bond");
e.printStackTrace();
return false;
}

Related

xamarin forms geolocation won't ask for gps to be turned on if the it's off

i'm trying to get the current location of the phone and then set the google maps view accordingly but if i have the gps off, it will just thrown an error instead of asking me to turn it on.
i have the access fine and coarse location permissions on android.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
var location = await Geolocation.GetLocationAsync(new GeolocationRequest(GeolocationAccuracy.Best));
I suggest you can detect whether GPS Location enable before you use it. I do one sample to check GPS isenbale or disable on Android platform for Xamarin.forms, the setting GPS location will open if GPS location disable.
Creating interface IGpsDependencyService in shared code.
public interface IGpsDependencyService
{
void OpenSettings();
bool IsGpsEnable();
}
Implement this interface on Android Platform, the platform implementations must be registered with the DependencyService, so that Xamarin.Forms can locate them at runtime.
[assembly: Dependency(typeof(GpsDependencyService))]
namespace FormsSample.Droid
{
public class GpsDependencyService : IGpsDependencyService
{
public bool IsGpsEnable()
{
LocationManager locationManager = (LocationManager)Android.App.Application.Context.GetSystemService(Context.LocationService);
return locationManager.IsProviderEnabled(LocationManager.GpsProvider);
}
public void OpenSettings()
{
Intent intent = new Intent(Android.Provider.Settings.ActionLocat‌​ionSourceSettings);
intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask);
try
{
Android.App.Application.Context.StartActivity(intent);
}
catch (ActivityNotFoundException activityNotFoundException)
{
System.Diagnostics.Debug.WriteLine(activityNotFoundException.Message);
Android.Widget.Toast.MakeText(Android.App.Application.Context, "Error: Gps Activity", Android.Widget.ToastLength.Short).Show();
}
}
}
}
To check GPS location, I use Plugin.Permissions to check location permission.
private async void Button_OnClicked(object sender, EventArgs e)
{
//var results = await CrossGeolocator.Current.GetPositionAsync(TimeSpan.FromSeconds(10));
//LabelGeolocation.Text = "Lat: " + results.Latitude + " Long: " + results.Longitude;
bool IsGpsEnable = Xamarin.Forms.DependencyService.Get<IGpsDependencyService>().IsGpsEnable();
if (!IsGpsEnable)
{
DisplayAlert("Location service Denied", "Can not continue,please go to setting to open location service and try again.", "OK");
Xamarin.Forms.DependencyService.Get<IGpsDependencyService>().OpenSettings();
}
else
{
try
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);
if (status != PermissionStatus.Granted)
{
if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Location))
{
await DisplayAlert("Need location", "Gunna need that location", "OK");
}
var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Location);
status = results[Permission.Location];
}
if (status == PermissionStatus.Granted)
{
var results = await CrossGeolocator.Current.GetPositionAsync(TimeSpan.FromSeconds(10));
LabelGeolocation.Text = "Lat: " + results.Latitude + " Long: " + results.Longitude;
}
else if (status != PermissionStatus.Unknown)
{
await DisplayAlert("Location Denied", "Can not continue, try again.", "OK");
}
}
catch (Exception ex)
{
LabelGeolocation.Text = "Error: " + ex;
}
}
}
About checking GPS location on ios platform, you can take a look:
https://github.com/xamarin/Essentials/issues/1257

Check if renewable subscription is active with Xamarin.Forms (Plugin.InAppBilling)

I have a Xamarin.Forms application with a few renewable subscriptions. I am using the InAppBilling plugin to purchase these subscriptions. Now my questions is: (which I already asked in this post) How can I check if the renewable subscription is active? Thanks in advance.
Through the document, you can check the status by
var connected = await billing.ConnectAsync(ItemType.Subscription);:
Here is the example:
public async Task<bool> PurchaseItem(string productId, string payload)
{
var billing = CrossInAppBilling.Current;
try
{
var connected = await billing.ConnectAsync(ItemType.InAppPurchase);
if (!connected)
{
//we are offline or can't connect, don't try to purchase
return false;
}
//check purchases
var purchase = await billing.PurchaseAsync(productId, ItemType.InAppPurchase, payload);
//possibility that a null came through.
if(purchase == null)
{
//did not purchase
}
else if(purchase.State == PurchaseState.Purchased)
{
//purchased!
}
}
catch (InAppBillingPurchaseException purchaseEx)
{
//Billing Exception handle this based on the type
Debug.WriteLine("Error: " + purchaseEx);
}
catch (Exception ex)
{
//Something else has gone wrong, log it
Debug.WriteLine("Issue connecting: " + ex);
}
finally
{
await billing.DisconnectAsync();
}

DatabaseIOException When Executing Query "Delete"

Can anybody help telling me what is wrong with my code? I am trying to connect to SQLite database, and executing some queries. when trying to create and open the database, create and insert the table, no exception returned. but when I try to execute delete statement,
DatabaseIOException: File system error (12)
always returned. I don't know the cause of the exception exactly. would you tell me what usually cause this kind of exception? I don't even know when I need to close the database and when I don't need to. this solution also makes me confused.
here is my code:
public class DatabaseManager {
Logger log = new Logger();
Database db;
public DatabaseManager() {
createDatabase();
}
private void createDatabase() {
// Determine if an SDCard is present
boolean sdCardPresent = false;
String root = null;
Enumeration enum = FileSystemRegistry.listRoots();
while (enum.hasMoreElements()) {
root = (String) enum.nextElement();
if(root.equalsIgnoreCase("sdcard/")) {
sdCardPresent = true;
}
}
if(!sdCardPresent) {
alert("This application requires an SD card to be present. Exiting application...");
}
else {
try {
URI uri = URI.create("/SDCard/databases/MyAdvanceUI/myadvanceui.db");
db = DatabaseFactory.openOrCreate(uri);
db.close();
//alert("Database OK!");
} catch (Exception e) {
// TODO Auto-generated catch block
//alert("Exception in createDatabase(): " + e);
}
}
}
private void alert(final String message) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.inform(message);
System.exit(0);
}
});
}
private void createTableTask() {
try {
URI uri = URI.create("/SDCard/databases/MyAdvanceUI/myadvanceui.db");
db = DatabaseFactory.open(uri);
Statement st = db.createStatement("CREATE TABLE IF NOT EXISTS t_task (id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "client TEXT, task TEXT)");
st.prepare();
st.execute();
st.close();
db.close();
//alert("Table Task created!");
} catch (Exception e) {
// TODO: handle exception
//alert("Exception in createTableTask(): " + e);
}
}
private void insertTableTask() {
String[] clients = { "Budi Setiawan", "Dian Kusuma", "Joko Ahmad", "Titi Haryanto", "Wahyu" };
String[] tasks = {
"Penawaran terhadap instalasi server",
"Follow up untuk keperluan produk terbaru",
"Pendekatan untuk membina relasi",
"Penawaran jasa maintenance",
"Penawaran terhadap instalasi database"
};
try {
URI uri = URI.create("/SDCard/databases/MyAdvanceUI/myadvanceui.db");
db = DatabaseFactory.open(uri);
for(int i = 0; i < clients.length; i++) {
Statement st = db.createStatement("INSERT INTO t_task (client, task) VALUES (?, ?)");
st.prepare();
st.bind(1, clients[i]);
st.bind(2, tasks[i]);
st.execute();
st.close();
}
db.close();
} catch (Exception e) {
// TODO: handle exception
//alert("Exception in insertTableTask(): " + e);
}
}
public void loadInitialData() {
createTableTask();
insertTableTask();
}
public Cursor getTasks() {
// TODO Auto-generated method stub
Cursor results = null;
try {
URI uri = URI.create("/SDCard/databases/MyAdvanceUI/myadvanceui.db");
db = DatabaseFactory.open(uri);
Statement st = db.createStatement("SELECT client, task FROM t_task");
st.prepare();
results = st.getCursor();
return results;
} catch (Exception e) {
// TODO: handle exception
//alert("Exception: " + e);
}
return results;
}
public void delete(String string) {
// TODO Auto-generated method stub
try {
URI uri = URI.create("/SDCard/databases/MyAdvanceUI/myadvanceui.db");
db = DatabaseFactory.open(uri);
Statement st = db.createStatement("DELETE FROM t_task WHERE client=?");
st.prepare();
st.bind(1, string);
st.execute();
} catch (Exception e) {
// TODO: handle exception
alert("Exception: " + e);
}
}
}
thank you for your help.
I don't see that you close the statement and close the database after select and delete actions. Most probably you can't open database because it wasn't closed correctly.
Big warning SD card isn't available when user mounted devices to PC as external drive. Some devices are going without SD card preinstalled. DB operations are really slow on 5 OS devices. Your alert method code wan't close db what could be issue to open it after on the next application start.
Warning As #pankar mentioned in comment you should add finally {} where you will close resources for sure. In your current implementation if you get exception in execution you will never close database.
Big improvements You don't need to create and prepare statement every loop. Just do it before for. Do bind and execute every loop. And close statement after for.
Improvements You could keep one opened db during application run cycle. It will save you some line of code and time for opening closing.
Notation It's bad practice to have parameter named like 'string'. I would rename it to something more meaningful.

Push Notification, alert message not receiving on iPhone

I am working on Push notifications for iPhone. I am sending notification on button click, but the iPhone developer is not receiving the alert message. Can anyone plz help me?
This is my method --
protected void btnPush_Click(object sender, EventArgs e)
{
string devicetoken = "bhsdse78 d52c6a34 273de5f7 27947945 24736e36 33d93a6c 3147a416 434995eb";
try
{
if (devicetoken != "")
{
//lblError.Visible = false;
string p12FileName = "D:/Worksapace/Coupzila/Certificates(3).p12"; // change this to reflect your own certificate
string p12Password = "seas"; // change this
bool sandBox = true;
int numConnections = 1; // you can change the number of connections here
var notificationService = new NotificationService(sandBox, p12FileName, p12Password, numConnections);
var deviceToken = devicetoken; // put in your device token here
var notification = new Notification(deviceToken);
notification.Payload.Alert.Body = "Hi this is push notification test message.";
notification.Payload.Sound = "default";
notification.Payload.Badge = 1;
notification.Payload.HideActionButton = true;
if (notificationService.QueueNotification(notification))
{ }
else
{ }
// This ensures any queued notifications get sent befor the connections are closed
notificationService.Close();
notificationService.Dispose();
}
else
{
//lblError.Visible = true;
}
}
catch (Exception ex)
{
}
}
This method is running successfully, but not getting notifications on iPhone, Whtz problem in my code?
Help me out, Thanks in advance
First, Remove the empty characters from your deviceToken.
Second, Put # sign for your fileName;
string p12FileName = #"D:/Worksapace/Coupzila/Certificates(3).p12";
And for the last step implement your catch, like;
catch (Exception ex)
{
MessageBox.Show("There is an error from push notification. Details:\n" + ex);
}
And good with Apple.

interesting service behaviour in silverlight

I have a Silverlight project which takes some encrypted string thru its Service Reference: DataService (service which is done in an ASP.NET project).
The method from TransactionServices.cs to get the encrypted string is:
public void GetEncryptedString(string original)
{
DataService.DataServiceClient dataSvc = WebServiceHelper.Create();
dataSvc.GetEncryptedStringCompleted += new EventHandler<SpendAnalyzer.DataService.GetEncryptedStringCompletedEventArgs>(dataSvc_GetEncryptedStringCompleted);
dataSvc.GetEncryptedStringAsync(original);
}
On completing, put the result in encodedString var (which is initialized with an empty value):
void dataSvc_GetEncryptedStringCompleted(object sender, SpendAnalyzer.DataService.GetEncryptedStringCompletedEventArgs e)
{
if (e.Error == null)
{
try
{
if (e.Result == null) return;
this.encodedString = e.Result;
}
catch (Exception ex)
{
Logger.Error("TransactionService.cs: dataSvc_GetEncryptedStringCompleted: {0} - {1}",
ex.Message, ex.StackTrace);
MessageBox.Show(ex.ToString());
}
}
}
Now I want to get the encoded string from my MainPage.xaml like:
TransactionService ts = new TransactionService();
ts.GetEncryptedString(url);
Console.WriteLine(ts.encodedString);
I do not uderstand why ts.encodedString is empty. When I do the debug I see that it actually prints out empty and AFTER that it goes to the void dataSvc_GetEncryptedStringCompleted to take the result and fill it.
Can you point me what I've done wrong? Is there a way to wait for the encodedString to be fetched and only after that to continue?
Thanks a lot.
When you call the ts.GetEncryptedString(url); you just started async operation. And therefor the value you are accessing is will be set only in the callback method.
But you access it before the value is modified by the callback.
The solution which I am using will looks similar to folowing:
Redefine the GetEncryptedString method signature.
public void GetEncryptedString(string original, Action callback)
{
DataService.DataServiceClient dataSvc = WebServiceHelper.Create();
dataSvc.GetEncryptedStringCompleted += (o,e) =>
{
dataSvc_GetEncryptedStringCompleted(o,e);
callback();
}
dataSvc.GetEncryptedStringAsync(original);
}
Call it like this:
ts.GetEncryptedString(url, OtherLogicDependantOnResult);
where
OtherLogicDependantOnResult is
void OtherLogicDependantOnResult()
{
//... Code
}

Resources