Xamarin – Day 3 Advance Android

This post will cover below concepts on Xamarin Android

  • Fragments
  • Why fragments
  • Catering to multiple form factors
  • Services
  • GPS
  • Maps
  • Camera

Fragments – Create a fragment

public static Fragment1 NewInstance()

{

var frag = new Fragment1 { Arguments = new Bundle() };

return frag;

}

public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)

{

base.OnCreateView(inflater, container, savedInstanceState);

var view = inflater.Inflate(Resource.Layout.fragment1View, null);

return view;

}

Container View

<?xml version=”1.0″ encoding=”utf-8″?>

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;

android:orientation=”vertical”

android:layoutwidth=”fillparent”

android:layoutheight=”fillparent”

android:minWidth=”25px”

android:minHeight=”25px”

android:background=”#fff000″>

<TextView

android:text=”Fragment1″

android:textAppearance=”?android:attr/textAppearanceLarge”

android:layoutwidth=”matchparent”

android:layoutheight=”wrapcontent”

android:id=”@+id/textView1″

android:layout_marginBottom=”18.4dp” />

</LinearLayout>

Invoking via code

<FrameLayout

android:minWidth=”25px”

android:minHeight=”25px”

android:layoutwidth=”wrapcontent”

android:layoutheight=”wrapcontent”

android:id=”@+id/frameLayout1″>

void showFragment(int position)

{

Fragment fragment = null;

switch (position)

{

case 0:

fragment = fragment1.NewInstance();

break;

case 1:

fragment = Fragment2.NewInstance();

break;

}

FragmentManager.BeginTransaction()

.Replace(Resource.Id.frameLayout1, fragment)

.Commit();

}

using fragment in view axml

<fragment

class=”androidfragmentpoc.Fragments.fragment1″

android:id=”@+id/fragment1″

android:layoutwidth=”wrapcontent”

android:layoutheight=”wrapcontent” />

<FrameLayout

android:minWidth=”25px”

android:minHeight=”25px”

android:layoutwidth=”wrapcontent”

android:layoutheight=”wrapcontent”

android:id=”@+id/frameLayout1″>

<fragment

class=”androidfragmentpoc.Fragments.Fragment2″

android:id=”@+id/fragment2″

android:layoutwidth=”wrapcontent”

android:layoutheight=”wrapcontent” />

</FrameLayout>

Setting value to frag view

public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)

{

base.OnCreateView(inflater, container, savedInstanceState);

var view = inflater.Inflate(Resource.Layout.fragment2View, null);

var txt = view.FindViewById<TextView>(Resource.Id.textView1);

txt.Text = @”modified text”;

return view;

}

Using Service

[Service]

public class DemoService : Service

{

string tag = “DemoService”;

public override IBinder OnBind(Intent intent)

{

return null; //null started service

}

public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)

{

Log.Info(tag, “OnStartCommand()”);

showToast(“OnStartCommand()”);

showNotification(0, “services”, “OnStartCommand”);

DoWork();

//return base.OnStartCommand(intent, flags, startId);

return StartCommandResult.NotSticky;

}

public void DoWork()

{

Log.Info(tag, “Doing work”);

var t = new Thread(() =>

{

Thread.Sleep(2000);

Log.Info(tag, “Work complete”);

showNotification(1,”from thread”, “Work completed”);

StopSelf();

}

);

t.Start();

}

public override void OnDestroy()

{

Log.Info(tag, “OnDestroy()”);

base.OnDestroy();

showToast(“OnDestroy()”);

}

public void showToast(string message)

{

var myHandler = new Handler();

myHandler.Post(() =>

{

Toast.MakeText(this, message, ToastLength.Long).Show();

});

}

public void showNotification(int notificationId, string title, string message)

{

// Instantiate the builder and set notification elements:

Notification.Builder builder = new Notification.Builder(this)

.SetContentTitle(title)

.SetContentText(message)

.SetSmallIcon(Resource.Drawable.Icon);

// Build the notification:

Notification notification = builder.Notification;

// Get the notification manager:

NotificationManager notificationManager =

GetSystemService(Context.NotificationService) as NotificationManager;

// Publish the notification:

//const int notificationId = 0;

notificationManager.Notify(notificationId, notification);

}

}

void button2_Click(object sender, EventArgs e)

{

StopService(new Intent(this, typeof(DemoService)));

}

void button1_Click(object sender, EventArgs e)

{

StartService(new Intent(this, typeof(DemoService)));

}

using Location

implement ILocationListener in Activity

TextView latitude;

TextView longitude;

LocationManager locMgr;

protected override void OnCreate(Bundle bundle)

{

base.OnCreate(bundle);

SetContentView(Resource.Layout.locationView);

latitude = FindViewById<TextView>(Resource.Id.textView1);

longitude = FindViewById<TextView>(Resource.Id.textView2);

var b = FindViewById<Button>(Resource.Id.button1);

b.Click += (o,e)=>{

//string uri = string.Format(“google.streetview:cbll={0},{1}&cbp=1,yaw,,pitch,zoom&mz=20”, latitude, longitude);

string uri = string.Format(“geo:{0},{1}”, latitude, longitude);

var geoUri = Android.Net.Uri.Parse(uri);

var mapIntent = new Intent(Intent.ActionView, geoUri);

StartActivity(mapIntent);

};

getLocationProvider();

}

// set ACCESSFINELOCATION

string getLocationProvider()

{

Criteria locationCriteria = new Criteria();

locationCriteria.Accuracy = Accuracy.Coarse;

locationCriteria.PowerRequirement = Power.Medium;

locMgr = GetSystemService(Context.LocationService) as LocationManager;

var locationProvider = locMgr.GetBestProvider(locationCriteria, true);

if (locationProvider != null)

{

locMgr.RequestLocationUpdates(locationProvider, 2000, 1, this);

}

else

{

//Log.Info(Debug, “No location providers available”);

}

return locationProvider;

}

public void OnLocationChanged(Location location)

{

latitude.Text = “Latitude: ” + location.Latitude;

longitude.Text = “Longitude: ” + location.Longitude;

}

Using Camera

<uses-permission android:name=”android.permission.ACCESSFINELOCATION” />

<uses-permission android:name=”android.permission.WRITEEXTERNALSTORAGE” />

<uses-permission android:name=”android.permission.CAMERA” />

<?xml version=”1.0″ encoding=”utf-8″?>

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;

android:orientation=”vertical”

android:layoutwidth=”fillparent”

android:layoutheight=”fillparent”>

<Button

android:text=”Button”

android:layoutwidth=”matchparent”

android:layoutheight=”wrapcontent”

android:id=”@+id/button1″ />

<ImageView

android:src=”@android:drawable/icmenugallery”

android:layoutwidth=”matchparent”

android:layoutheight=”wrapcontent”

android:id=”@+id/imageView1″ />

</LinearLayout>

public class CameraActivity : Activity

{

string filePath = string.Empty;

File _dir;

File _file;

Bitmap bitmap;

ImageView imageView;

protected override void OnCreate(Bundle bundle)

{

base.OnCreate(bundle);

SetContentView(Resource.Layout.cameraView);

var b = FindViewById<Button>(Resource.Id.button1);

b.Click += (o, e) =>

{

TakeAPicture();

};

imageView = FindViewById<ImageView>(Resource.Id.imageView1);

}

private void CreateDirectoryForPictures()

{

_dir = new File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures), “CameraAppDemo”);

if (!_dir.Exists())

{

_dir.Mkdirs();

}

}

private void TakeAPicture()

{

CreateDirectoryForPictures();

Intent intent = new Intent(MediaStore.ActionImageCapture);

file = new File(dir, String.Format(“myPhoto_{0}.jpg”, Guid.NewGuid()));

intent.PutExtra(MediaStore.ExtraOutput, Android.Net.Uri.FromFile(_file));

StartActivityForResult(intent, 0);

}

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)

{

base.OnActivityResult(requestCode, resultCode, data);

// make it available in the gallery

Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);

Android.Net.Uri contentUri = Android.Net.Uri.FromFile(_file);

mediaScanIntent.SetData(contentUri);

SendBroadcast(mediaScanIntent);

// display in ImageView. We will resize the bitmap to fit the display

// Loading the full sized image will consume to much memory

// and cause the application to crash.

int height = Resources.DisplayMetrics.HeightPixels;

int width = imageView.Width;

bitmap = LoadAndResizeBitmap(_file.Path, width, height);

if (bitmap != null)

{

imageView.SetImageBitmap(bitmap);

bitmap = null;

}

}

public static Bitmap LoadAndResizeBitmap(string fileName, int width, int height)

{

// First we get the the dimensions of the file on disk

BitmapFactory.Options options = new BitmapFactory.Options { InJustDecodeBounds = true };

BitmapFactory.DecodeFile(fileName, options);

// Next we calculate the ratio that we need to resize the image by

// in order to fit the requested dimensions.

int outHeight = options.OutHeight;

int outWidth = options.OutWidth;

int inSampleSize = 1;

if (outHeight > height || outWidth > width)

{

inSampleSize = outWidth > outHeight

? outHeight / height
outWidth / width;

}

// Now we will load the image and have BitmapFactory resize it for us.

options.InSampleSize = inSampleSize;

options.InJustDecodeBounds = false;

Bitmap resizedBitmap = BitmapFactory.DecodeFile(fileName, options);

return resizedBitmap;

}

}