In this tutorial, we will learn how to pin Latitude and Longitude or Co-Ordinates in External maps in Xamarin.Forms. The Co-Ordinates are pinned with Google Maps in Android and Apple Maps in iOS.
External Maps Plugin:
This plugin is used to pin specific geo-location and Navigating user from current location to that specified location. James Montemongo had written a plugin to navigate users. But this plugin doesn’t have functionality to pin the specified location. So I have rewritten the plugin and you can find the plugin from GitHub and Nuget.
Platform Support:
It has the support for Android and iOS Platforms.
Xamarin.iOS - iOS 7+
Xamarin.Android - API 10+
Coding Part:
Steps:
I have split this part into 3 steps as in the following.
Step 1: Creating new Xamarin.Forms Projects.
Step 2: Setting up the plugin for Xamarin.Forms Application.
Step 3: Implementing the functionality to pin location.
Step 1
Create New Project by Selecting New -> Project -> Select Xamarin Cross Platform App and Click OK.
Then Select Android and iOS Platforms as shown below with Code Sharing Strategy as PCL or .Net Standard and Click OK.
Step 2
We will start coding for External Maps. Create New Xamarin Forms Project. Open Nuget Package Manager against the solution and do search for External Maps Plugin or Paste the following Nuget Installation.
Install-Package ExternalMapsPlugin -Version 1.0.0
Add this Plugin against Android & iOS Platforms.
Step 3
Open your XAML file and paste the following code. I have added a clicked event for the button to trigger or pin the specific co-ordinate to the map.
Here, Vannarapettai is the label for your location 10.7653, 79.0687 is Latitude & Longitude of the location respectively. 8 is the zoom level of your Application.
Demo
The Following screenshots demonstrates how this plugin works. You can download the source code of this article and post your comments about this article and Plugin.
Android
iOS
Download Code
You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.
September 25, 2018
Introduction: In this article, we will learn how to send Mail directly from Xamarin Android Application without any Intents. For this, ...
How to Send Mail directly from Android Application in Xamarin.Android
In this article, we will learn how to send Mail directly from Xamarin Android Application without any Intents. For this, we can MailKit to send mail directly.
MailKit:
MailKit is a cross-platform mail client library built on top of MimeKit. MailKit is a personal open source project that I have put thousands of hours into perfecting with the goal of making it the very best email framework for .NET.
Coding Part:
Steps:
I have split this article into 3 steps as in the following.
Step 1: Creating new Xamarin.Android Projects.
Step 2: Setting up the plugin for Xamarin.Android Application.
Step 3: Implementing Mail functionalities in Xamarin.Android Application.
Step 1: Creating new Xamarin.Android Projects
Create New Project by Selecting New Project Select Android App and Click OK.
Step 2: Setting up the plugin for Xamarin.Android Application
In this step, we will include the Mailkit plugin for Xamarin.Android Project. Open Nuget Package Manager against the project and do search for Mailkit and click install to add the library or Paste the following in Package Manager Console to install the Nuget plugin.
Install-Package MailKit
Step 3: Implementing Mail Functionalities in Xamarin.Android Application
In this part, we will see how to implement Mail functions to send mail.
Open your MainActivity.cs and Import the Following Packages.
using MimeKit;
using MailKit.Net.Smtp;
Then add/create an Async task class named as “MailAsyncTask” and add implement the override functions.
OnPreExecute
OnPostExecute
DoInBackground
Then add/paste the following code in DoInBackground method.
var message = new MimeMessage();
message.From.Add(new MailboxAddress("From", mainActivity.edtFrom.Text));
message.To.Add(new MailboxAddress("To", mainActivity.edtTo.Text));
message.Subject = mainActivity.edtSubject.Text;
message.Body = new TextPart("plain")
{
Text = mainActivity.edtMessage.Text
};
using (var client = new SmtpClient())
{
// For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect(host, port, false);
// Note: only needed if the SMTP server requires authentication
client.Authenticate(username, password);
client.Send(message);
client.Disconnect(true);
}
Here, we should provide host address, port and username & password if the SMTP server needs authentication.
The Mail Connections needed to be run with separate thread. So, I had done the call with “AsyncTask”. You can find the full code below.
Full code of the MailAsyncClass:
The following code shows how to implement Direct Mail functions in Xamarin.Android with AsyncTask.
class MailAsyncTask : AsyncTask
{
string username = "mail-id or username", password = "password", host = "smtp.gmail.com";
int port = 25;
MainActivity mainActivity;
ProgressDialog progressDialog;
public MailAsyncTask(MainActivity activity)
{
mainActivity = activity;
progressDialog = new ProgressDialog(mainActivity);
progressDialog.SetMessage("Sending...");
progressDialog.SetCancelable(false);
}
protected override void OnPreExecute()
{
base.OnPreExecute();
progressDialog.Show();
}
protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params)
{
try
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress("From", mainActivity.edtFrom.Text));
message.To.Add(new MailboxAddress("To", mainActivity.edtTo.Text));
message.Subject = mainActivity.edtSubject.Text;
message.Body = new TextPart("plain")
{
Text = mainActivity.edtMessage.Text
};
using (var client = new SmtpClient())
{
// For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect(host, port, false);
// Note: only needed if the SMTP server requires authentication
client.Authenticate(username, password);
client.Send(message);
client.Disconnect(true);
}
return "Successfully Sent";
}
catch (System.Exception ex)
{
return ex.Message;
}
}
protected override void OnPostExecute(Java.Lang.Object result)
{
base.OnPostExecute(result);
progressDialog.Dismiss();
mainActivity.edtFrom.Text = null;
mainActivity.edtTo.Text = null;
mainActivity.edtSubject.Text = null;
mainActivity.edtMessage.Text = null;
Toast.MakeText(mainActivity, "Email Succesfully Sent...", ToastLength.Short).Show();
}
}
The Mail class can be executed by the following code
new MailAsyncTask(this).Execute();
Download Code:
You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.
September 18, 2018
In this article, we will learn to load Base64 String Images into Images in Xamarin.Forms without using any External Plugins like FFMpe...
In this article, we will learn to load Base64 String Images into Images in Xamarin.Forms without using any External Plugins like FFMpeg Image Loader Plugin.
Base64 Images
Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding. To know more about Base64 Click Here.
Platform Support
The approach used here is done with Portable Library. So, it supports all the 3 (Android, iOS, and UWP) Platforms supported by Xamarin.Forms.
Without much introduction, we will skip into the coding part of this article.
Steps
I have explained the method to load base64 image in Image with 3 steps as shown below.
Step 1 - Creating new Xamarin.Forms Projects.
Step 2 - Creating a user interface with Xamarin.Forms.
Step 3 - Implementing the functionality to load Base64 Image.
Step 1 Creating new Xamarin.Forms Projects.
Create New Project by Selecting New >> Project >> Select Xamarin Cross-Platform App and Click OK.
Then Select Android and iOS Platforms as shown below with Code Sharing Strategy as PCL or .NET Standard and Click OK.
Step 2 Creating a user interface with Xamarin.Forms
Add Image Control to your Page, and here, I am going to add the control in MainPage.xaml. You can paste the codes shown below to create user interface for your page.
Step 3 implementing the functionality to load Base64 Image
In Xamarin.Forms, we can assign the source for Images by many ways like File Path, Image URL, From Resource Folder or Stream of Image.
We can convert the Base64 string into Stream of Image. That is array of Bytes (byte[]). We will use this method to assign Base64 image to Image Controls using the following code.
byte[] Base64Stream = Convert.FromBase64String(base64Image);
xfImage.Source = ImageSource.FromStream(() => new MemoryStream(Base64Stream));
Full Code of MainPage.xaml.cs
namespace Base64 {
public partial class MainPage: ContentPage {
string base64Image = "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";
public MainPage() {
InitializeComponent();
byte[] Base64Stream = Convert.FromBase64String(base64Image);
xfImage.Source = ImageSource.FromStream(() => new MemoryStream(Base64Stream));
}
}
}
The longest string shown here is the base 64 is encoded to the image
Convert.FromBase64String(base64Image) is used to convert base64 string byte[].
ImageSource.FromStream(() => new MemoryStream(Base64Stream)) is used to convert the byte[] to Image Stream and Stream is assigned to Image Control.
September 16, 2018
When considering how to build iOS and Android applications, many people think that the native languages, Objective-C, Swift, and Java, ...
When considering how to build iOS and Android applications, many people think that the native languages, Objective-C, Swift, and Java, are the only choice. However, over the past few years, an entire new ecosystem of platforms for building mobile applications has emerged.
Xamarin is unique in this space by offering a single language – C#, class library, and runtime that works across all three mobile platforms of iOS, Android, and Windows Phone (Windows Phone’s native language is already C#), while still compiling native (non-interpreted) applications that are performant enough even for demanding games.
Each of these platforms has a different feature set and each varies in its ability to write native applications – that is, applications that compile down to native code and that interop fluently with the underlying Java subsystem. For example, some platforms only allow apps to be built in HTML and JavaScript, whereas some are very low-level and only allow C/C++ code. Some platforms don’t even utilize the native control toolkit.
In Androidmads, we will not cover the basics of Xamarin App development. But, we will cover the advanced concepts of Xamarin as well as we will assist you, if you find any help with Xamarin Basics. And also we will see about Flutter App development.
In this article, we will learn how to create and use Clearable EditText without using any Third party library. It is very easy to implement and useful control for our application development.
Coding Part:
Steps:
I have split this part into 3 steps as in the following.
Creating New Project with Empty Activity.
Setting up the Library.
Implementation of Custom Control in Android.
Step 1: Creating New Project with Android Studio
Open Android Studio and Select Create new project.
Name the project as your wish and select your activity template.
Click “finish” button to create new project in Android Studio.
Step 2: Setting up the Firebase Library
In this part, we will see how to setup the library for the project.
Open your app level build.gradle file and add the following lines in dependencies to apply required libraries to your project.
Create a class named as ClearableEditText extend with AppCompatEditText as Parent.
Then open the class file and add the following code of lines.
public class ClearableEditText extends android.support.v7.widget.AppCompatEditText {
private Drawable drawableTemp;
private Drawable drawableRight;
int actionX, actionY;
private DrawableClickListener clickListener;
public ClearableEditText(Context context) {
super(context);
}
public ClearableEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ClearableEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
public void setCompoundDrawables(Drawable left, Drawable top,
Drawable right, Drawable bottom) {
if (right != null) {
drawableRight = right;
}
super.setCompoundDrawables(left, top, right, bottom);
}
@Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
if (text.toString().length() > 0) {
drawableRight = drawableTemp;
setCompoundDrawables(null, null, drawableRight, null);
} else {
drawableTemp = drawableRight;
setCompoundDrawables(null, null, null, null);
}
super.onTextChanged(text, start, lengthBefore, lengthAfter);
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent event) {
Rect bounds;
if (event.getAction() == MotionEvent.ACTION_DOWN) {
actionX = (int) event.getX();
actionY = (int) event.getY();
if (drawableRight != null) {
bounds = drawableRight.getBounds();
int x, y;
int extraTapArea = 13;
/*
IF USER CLICKS JUST OUT SIDE THE RECTANGLE OF THE DRAWABLE
THAN ADD X AND SUBTRACT THE Y WITH SOME VALUE SO THAT AFTER
CALCULATING X AND Y CO-ORDINATE LIES INTO THE DRAWBABLE
BOUND. - this process help to increase the tappable area of
the rectangle.
*/
x = actionX + extraTapArea;
y = actionY - extraTapArea;
/*
Since this is right drawable subtract the value of x from the width
of view. so that width - tapped_area will result in x co-ordinate in drawable bound.
*/
x = getWidth() - x;
/*x can be negative if user taps at x co-ordinate just near the width.
e.g views width = 300 and user taps 290. Then as per previous calculation
290 + 13 = 303. So subtract X from getWidth() will result in negative value.
So to avoid this add the value previous added when x goes negative.
*/
if (x <= 0) {
x += extraTapArea;
}
/*
If result after calculating for extra tap-able area is negative.
assign the original value so that after subtracting
extra tapping area value doesn't go into negative value.
*/
if (y <= 0)
y = actionY;
/*
If drawable bounds contains the x and y points then move ahead.
*/
if (bounds.contains(x, y) && clickListener != null) {
clickListener.onClick();
event.setAction(MotionEvent.ACTION_CANCEL);
return false;
}
return super.onTouchEvent(event);
}
}
return super.onTouchEvent(event);
}
@Override
protected void finalize() throws Throwable {
drawableRight = null;
super.finalize();
}
public void setDrawableClickListener(DrawableClickListener listener) {
this.clickListener = listener;
}
public interface DrawableClickListener {
void onClick();
}
}
Here, I have created DrawableClickListener interface which is used to intimate users when they clicked the Drawable icon of the EditText control.
Open your activity_main.xml file and add the following lines.
The Layout Preview looks like in the below screenshot
This control will shows the cancel “icon” when the control has typed text and “icon” will hide when the control has no text.
Then open your MainActivity.java file and initialize your control like the following.
final TextInputLayout textInputLayout = findViewById(R.id.text_input_layout);
final ClearableEditText editText = findViewById(R.id.edit_text);
final Button button = findViewById(R.id.button);
The cancel icon will appear when the user types the data. Add the following Drawable click listener as look like in the following.
As discussed in our previous posts, we have learned how to perform email authentication and phone number authentication with firebase in android. In this article, we will how to perform Google Plus authentication in Android.
Firebase facilities Developers to manage Google plus Authentication in Easy way. Before starting, we have add or enable Google plus Authentication in Firebase console.
Firebase Setup:
Before start coding, we have to setup firebase for android and enable Phone Authentication. If you are new to firebase, the following link will be useful to know the method for setting up the project in firebase.
After setting up, open Authentication sign in method and enable phone authentication method as shown in the following figure.
You should Add SHA Fingerprint in your application. The following terminal will be used to get the SHA Fingerprint with Command Prompt in Windows for debug mode.
Step 3: Implementation of Firebase
Google plus Authentication:
Initialize Google Sign in Client with Google Sign
in options and Firebase Auth Client like shown in below snippet.
//first we initialized the Firebase Auth object
FirebaseAuth mAuth = FirebaseAuth.getInstance();
//Then we need a GoogleSignInOptions object
//And we need to build it as below
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
//Then we will get the GoogleSignInClient object from GoogleSignIn class
GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
You must pass your server's client ID to the requestIdToken method. To find the OAuth 2.0 client ID: Open the Credentials page in the API Console. The Web application type client ID is your backend server's OAuth 2.0 client ID.
Then add the following code to initiate Google sign in.
//getting the google signin intent
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
//starting the activity for result
startActivityForResult(signInIntent, RC_SIGN_IN);
Add the onActivityResult as shown below
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//if the requestCode is the Google Sign In code that we defined at starting
if (requestCode == RC_SIGN_IN) {
//Getting the GoogleSignIn Task
Task task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
//Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
//authenticating with firebase
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
Log.v("API Exception", e.toString());
Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
After a user successfully signs in, get an ID token from the GoogleSignInAccount object, exchange it for a Firebase credential, and authenticate with Firebase using the Firebase credential.
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
//getting the auth credential
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
//Now using firebase we are signing in the user here
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
if (mAuth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}
If the user is authenticated with Google Plus Sign In successfully, then login screen is redirected to the next activity.
To retrieve user details like name, profile picture, mail id through Firebase, use the following snippets.
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
assert user != null;
textName.setText(user.getDisplayName());
textEmail.setText(user.getEmail());
Picasso.get().load(user.getPhotoUrl()).into(imageView);
Here,
I have used Picasso Image Loading Library to load images. To more
click here.
Download Code:
You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.
August 15, 2018
Introduction: In this article, we will learn how use Kenburnsview in Android using Kotlin. Kenburnsview is an awesome Android library ...
In
this article, we will learn how use Kenburnsview in Android using
Kotlin. Kenburnsview is an awesome Android library that provides an
extension to ImageView that
creates an immersive experience by animating its Drawable using
theKen
Burns Effect.
Coding Part:
I have divided the coding part
into 3 steps as shown in the following.
Creating new project with Kotlin
Support.
Setting up the project with
Kenburnsview
Library.
Implementing KenburnsView with
Kotlin.
Step 1: Creating new project
with Kotlin:
Open Android Studio and Select Create new project.
Name the project as your wish and tick the
Kotlin checkbox support.
Then Select your Activity type (For
Example: Navigation Drawer
Activity, Empty Activity, etc.).
Then Click “finish”
button to create new project in Android Studio.
Step 2: Setting up the project
with AndroidManifest:
We will add the following lines to your app
level build.gradle to add KenburnsView library to your project.
In
this article, we will learn how to create a music previewer like
Google play music and register the app as Music Player to the phone.
Registering mobile app as Music Player will show our app in
suggestions while opening audio files.
Intent
Filter:
Registering
app as music player will be achieved by intent-filters in
AndroidManifest.xml against
our activity. To know more about Intent-Filters, read the link.
Coding Part:
Steps:
I
have split this part into 3 steps as in the following.
Step
1: Creating New Project with Empty
Activity.
Step
2: Implementation of Music Previewer
UI.
Step
3: Setting up Manifest with Intent
Filters.
Step
4: Implementation of Music Previewer in
Android.
Step
1: Creating New Project with Android Studio
Open Android Studio and Select Create new
project.
Name the project as your wish and select your
activity template.
Click “finish”
button to create new project in Android Studio.
Step
2: Implementation of Music Previewer UI
In
this part, we will see how to create a dialog for music previewer.
We will create an activity named as
MainActivity.java and
we need this activity to be show like Dialog. So, we have add the
following lines in styles.xml
file.
Theme.Appcompat.Light.Dialog
is used to apply dialog like style to an activity.
By default, the dialog style applied based on
children width. To apply full width to the dialog, use
windowMinWidthMinor key
with value 90%.
In the same way, windowCloseOnTouchOutside
is used to handle dialog cancel on touch outside of the views. It is
similar setCancelableOnTouchOutside
method for dialogs.
Then open your layout file (for example:
activity_main.xml) and add the followings lines.
Then
click Run to view the output activity as dialog in the following
figure.
Step 3: Setting up manifest with
Intent-Filter:
In
this step, we will learn How to apply intent-filter to register your
music player app. The following line of codes will help us to
register the app.
Selected
song can be played with start method in media player API.
mp.start();
Media
Player can be paused using pause method in media player API.
if (mp.isPlaying()) {
mp.pause();
}
Then
click Run or Shift + F10 to deploy the app in debug mode. Close your
app and select any audio file you want to open and select your app.
Now you can find your music player works fine.
Next
we will see, how to get the details of the selected audio file.
MediaMetadataRetriever is
used here.
The
MediaMetaDataRetriever can be initialized like below.
metaRetriever = new MediaMetadataRetriever();
metaRetriever.setDataSource(filePath);
Song’s
album can be retrieved using the following code.
In this article, we will learn how to generate QR Code in Android. Quick Response Code (QR Code in short) is a 2-Dimensional matrix type barcode used to store data. It is more popular because of its storage capacity and fast readability.
Zxing & QR Generator Library:
Zebra Crossing (Zxing) is an awesome library used to generate and read QR codes in mobile apps. But it is bigger in size. So, we have to go for another one, QR Generator which is a tiny, open source library. In this article, we will learn how to create & save the QR Code in Android programmatically.
Steps:
I have split this part into 4 steps as in the following.
Creating a New Project with Empty Activity.
Setting up the library and manifest.
Generating QR Code.
Saving QR Code.
Step 1 - Creating New Project with Empty Activity
Open Android Studio and Select create a new project.
Name the project as per your wish and select an Empty activity.
Click “finish” button to create a new project in Android Studio.
Step 2 - Setting up the library and manifest
Open App level gradle file and import the library.
qrImage is an ImageView used to preview the generated QR code bitmap.
Step 4 - Saving QR Code
QR Generator has an option to save the generated QR Code Bitmap to storage using the following lines.
// Save with location, value, bitmap returned and type of Image(JPG/PNG).
QRGSaver.save(savePath, edtValue.getText().toString().trim(), bitmap, QRGContents.ImageType.IMAGE_JPEG);
We can save QR Code in PNG & JPG format also. We have to handle runtime permissions from Android version 6.0.
In
this article, we will learn how perform AsyncTask in android with
Kotlin. Async task is used to perform some asynchronous tasks without
blocking the main thread. It is very useful in android development.
Similar to java, the same code can be used in Kotlin with some minor
modifications.
Coding Part:
I have divided the coding part
into 3 steps as shown in the following.
Creating new project with Kotlin
Support.
Setting up the project with
AndroidManifest.
Implementing Async tasks with
Kotlin.
Without any delay, we will start
coding for Kotlin AsyncTask.
Step 1: Creating new project with Kotlin:
Open Android Studio and Select Create new project.
Name
the project as your wish and tick the
Kotlin checkbox support.
Then
Select your Activity type (For
Example: Navigation Drawer
Activity, Empty Activity, etc.).
Then Click “finish”
button to create new project in Android Studio.
Step 2: Setting up the project
with AndroidManifest:
Now, we will add the internet permission in
Android Manifest file. Because we will see the example with URL
Connection. Just open your AndroidManifest.xmlfile and add the following line.
I have included a Button and TextView in my layout
(activity_main.xml) file.Here,
Button and TextView is used to call the API and display the result
from the API
Follow Us
Were this world an endless plain, and by sailing eastward we could for ever reach new distances