Splash Screen in Xamarin.Forms cross platform app (Android & iOS)

Practically there is no way to show Splash Screen/ Launch Screen using Xamarin.Forms because Xamarin.Forms libraries load after loading of AppDelegate (iOS) or MainActivity (Android) is completed. There is no point in showing splash screen at this point of application lifecycle because splash screens are meant to be displayed while app libraries are loading and we don’t want to show users a blank dark screen.

Keeping that in mind we have to configure it separately in each platform. Our splash screen will contain a solid colored background and a logo placed on center of the screen. Follow below links for detailed walk-through to add splash screen on each of he platform. Keep on reading

Add Splash Screen in Xamarin.Forms cross platform app – iOS

For showing splash screen in Xamarin forms iOS app we will need to follow below steps

  • Prepare/ Gather Images

We will be preparing our splash screen with a logo and solid color filled background. So for that we have two options that is prepare image for each of resolution type suggested by Apple or have and PDF format vector image through other resolutions are generated at run time. Keep in mind that PDF vector option will work only for iOS 8 and later. Keep on reading

Sample Code – Android share action with chooser to display system default share chooser dialog

This post is for helping those you are looking to implement share feature in there android application and ending up with default ShareActionProvider which is too basic and doesn’t look good at all.

Solution to this problem is “chooser”. below is the sample of how you can share any data with ACTION_SEND intent by setting text and subject and at the end call start activity with createChooser.

      Intent sendIntent = new Intent();
      sendIntent.setAction(Intent.ACTION_SEND);
      String text = "";
      String url = "";
      sendIntent.putExtra(Intent.EXTRA_SUBJECT, text);
      sendIntent.putExtra(Intent.EXTRA_TEXT, text + " nn" + url);
      sendIntent.setType("text/plain");
      context.startActivity(Intent.createChooser(sendIntent, "Share"));

There are many advantages of using chooser

  • Even if you has selected any default application of this action your application will share chooser dialog so that user can select any other application without going to settings
  • You have option to set title for your share action chooser dialog
  • If no matching application found (I don’t think if this will happen to anyone in real world) then android displays a system message.

Send FCM data message & notification to Android, iOS & Web in PHP

In our previous article we learnt how to send FCM data message notification from your server to FCM server using C#. Now for those you want to use PHP instead of C# to send FCM notification we have prepared a fairly simple class.

You just need to follow below four steps and you are done.

  1. Create an object of fcm class
  2. Call setIds method (passing array of registration ids) to set registration ids of your devices
  3. Call setData method to set your notification title, message and id.
  4. Call send method
class fcm
{
	private $url = "https://fcm.googleapis.com/fcm/send";
	private $ids = array();
	private $data = array();
	
	public function setIds($ids)
	{
		$this->ids = $ids;
	}

	public function send()
	{
		if (empty($this->ids))
		{
			return "no id";
		}

		$post = array(
			'registration_ids'  => $this->ids,
			'data'              => $this->data,
		);

		$headers = array(
			'Authorization: key=' . GOOGLE_API_KEY,
			'Content-Type: application/json'
		);
      
		$ch = curl_init();

		curl_setopt( $ch, CURLOPT_URL, $this->url);
		curl_setopt( $ch, CURLOPT_POST, true);
		curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($post));

		// Disabling SSL Certificate support temporarly
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

		$result = curl_exec($ch);
		
		if (curl_errno($ch)) 
		{
			$error = curl_error($ch);
			return $error;
		}

		curl_close($ch);

		$obj = json_decode($result, true);

		return "sent on: " . $obj['success'] . " devices";
	}

	public function setData($title, $msg, $id)
	{
		$this->data = array(
			"title" => $$title,
			"msg" => $msg,
			"id" => $id
		);
	}
}

Send notification on Android, iOS and Web using FCM

Few month before Google has launched its new cloud messaging platform Firebase Cloud messaging which will replace its current cloud messaging system Google Cloud Messaging. Gogle has not yet deprecated GCM but it has stopped support on this platform and suggested all developers to use FCM from now onward.

Although google has provided interface to send FCM notification from its console itself but there are some limitations. Actually google has divided notification system in two types:

  1. Notification message
  2. Data messages

=&0=& is simple message which contains a text which will be displayed in the notification area of the device along with some other fields like notification title and display icon. We don’t need to handle them on client app. FCM will catch and display it automatically. This type of message can be sent directly from FCM Console. Just select your project and go to notification tab.

A notification message will look like this:

{
    "to" : "yourclientregistrationid...",
    "notification" : {
      "body" : "notification body",
      "title" : "notification title",
      "icon" : "displayicon"
    }
}

=&1=& are more powerful where we can send any data we want to send in json format. Maximum payload for data messaged could be 4KB. This type of message need to be send via your own code.

A data message will look similar to this:

{
    "to" : "yourclientregistrationid...",
    "data" : {
      "field1" : "your content",
      "field2" : "your content",
      "field3" : "your content"
    }
}

You can see the notification is replaced by data and unlike notification there can be any number of field with any name which you can handle in your client app code.

In next Article we will discuss how to send data notification in C# and PHP

Adding Share Action on Android Application ActionBar (appcompat v7)

Adding share action on android application action bar is simple and straight forward.

There are mainly 3 steps that you have to follow:

1. Add Share Action Item in your menu

To add share action item in your menu simply add below item in your menu layout:

<item
	android:id="@+id/menu_item_share"
	app:showAsAction="ifRoom"
	android:title="Share"
	app:actionProviderClass="android.support.v7.widget.ShareActionProvider" />

And don’t forget to add res-auto schema on your menu. Your final menu layout should contain below details:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:app="http://schemas.android.com/apk/res-auto"
	xmlns:tools="http://schemas.android.com/tools">
	<item
		android:id="@+id/menu_item_share"
		app:showAsAction="ifRoom"
		android:title="Share"
		app:actionProviderClass="android.support.v7.widget.ShareActionProvider" />
</menu>

You can set showAsAction to any other value like always, never, withText etc
2. Create ShareActionProvider in your activity

No you have to create ShareActionProvider in your activity where you want to show and handle action share event.

For that first declare ShareActionProvider object

private ShareActionProvider mShareActionProvider;

override onCreateOptionMenu in your activity and add below code:

@Override
public boolean onCreateOptionsMenu(Menu menu) 
{
	// Inflate menu resource file.
	getMenuInflater().inflate(R.menu.menu_main, menu);

	// Locate MenuItem with ShareActionProvider
	MenuItem item = menu.findItem(R.id.menu_item_share);

	// Fetch and store ShareActionProvider
	mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item);

	setShareIntent();
	// Return true to display menu
	return true;
}

Here menu_main should be your menu xml file name and menu_item_share is the id of share item added in the menu.

You many notice that we have called a method setShareIntent at the end just before returning. This is not an inbuilt method. We will define this in next step.

3. Set Share Intent

Here we will set the intent of the share action so that we can control what will be shared if user proceeds to go further with sharing.

private void setShareIntent() 
{
	if (mShareActionProvider != null) 
	{
		Intent myShareIntent = new Intent(Intent.ACTION_SEND);
		myShareIntent.setType("text/plain");

		myShareIntent.putExtra(Intent.EXTRA_SUBJECT, "");
		myShareIntent.putExtra(Intent.EXTRA_TEXT, "");

		mShareActionProvider.setShareIntent(myShareIntent);
	}
}

You can specify different share intent type like in our case we have set text/plain because we are sharing plain text. Similarly you can set other type like view, images etc.

After that put extras based on based on your share intent type. For text/plain we have set subject and text.

=&0=& Whenever in your activity life cycle if your share content (subject and text in our case) is changed just call this method setShareIntent, no need to create ShareActionProvider again.

Visual Studio 15 Preview 3 released on 7th July 2016

Microsoft has released its preview 3 of Visual Studio 15. Yes it is Visual Studio 15 is upcoming version of Microsoft Visual Studio after Visual Studio 2015.

Being one of the most user friendly and feature rich IDE for application development Visual Studio is one of the most successful product of Microsoft. Now they are stepping to become next generation universal IDE which will be able to provide development on any platform and language. This is because in this version Microsoft has included feature to import iOS code from xcode (isn’t it a great new for all visual studio fans who want to use Visual studio as iOS development IDE?).

Here is the list of some new feature and enhancements you will get in visual studio 2015:

1. Visual Studio Tools for Apache Cordova

It will come with Apache Cordova 6.1.1 so all new projects which you will create will target Cordova 6.1.1. Apart from that you will be able any plugin using their npm package name

One thing which we should take care of is that it does not support Windows  Store 8.1 application so you have to update your  Cordova project to target Windows 10.

2. Visual Studio Tools for Universal Windows App Development

Microsoft team has done many improvements based on feedback they got from users and now there are full list of new features as well for the users. One of them is updated .NET native chain which will provide improved performance for universal windows apps.

3. Android Development Support

Now Android project support Gradle to builds .apk and .aar

4. iOS Development Support

A new entry point wizard is introduced to import existing iOS projects developed in xcode. This is not the only thing there are lot more to try and for that you have to downloadVisual Studio 15

5. Improvements in C# and Visual Basic

There is very big list specially in this category which we can not describe here. One major thing which everyone would love (atleast I am very excited after knowing this) is now you can break strings in multiple concatenated strings without manually writing + sign every time. Just put your cursor where you want to split the string and press enter it will automatically do the rest. Sounds good!!!

6. Improved Feedback Workflow

This visual studio version has better and improve feedback collaboration and followup system.

7. NuGet 3.4

Now you will get NuGet 3.4 with this version of visual studio. This version of NuGet supports Android and iOS build action in contentFile element and running NuGet in Linux and Apple environment. There are many more features and enhancements you will get.

8. Debugging and Diagnostic

Now you can condition so that debugger will break only when specified condition is true.
There is new exception introduced to see exception information in a compact dialog with instant access to inner exception.

Image Source

9. IDE Improvements

Now visual studio will load 30 to 35% faster on first launch. There is all new version control status bar to keep track of uncommitted work ad make it easier to publish local repositories.

10. And Many More

This is not all there are many more features you will get in this full bundled visual studio package. You can check complete list here
https://www.visualstudio.com/en-us/news/releasenotes/vs15-relnotes
Article Source

Speed up Android WebView App by localising static resources

Recently I was developing an android app which was using a WebView to display some graphs on dashboard. Rest of application was build on native android code and only this dashboard portion was using webview to load a specific URL where dashboard graphs were displayed.

I used webview to load graphs because creating graphs is too complicated in android as compared to web. Also most of the android graph tools I found were not created to draw attractive graphs.

So I used WebView to display my graphs on android app but things become even worse because I was using this webview dashboard in my main activity. So every time when I open the app it was taking almost 15 to 20 seconds to load and this time is long enough to make users a safe distance from your app.

After searching for some time and doing some tweaking I reached to one of the most effective solution (at-least for my app scenario) and want other to get benefit from it.

=&0=& So first thing we should do is copy all the external static resources (like css, js, fonts files etc) of the webpage to assets folder of your android project. If your project doesn’t have assets folder then you can create one on app root and copy all external static content of your page on this file.

This is specially helpful because most of the time a page takes to load is because of loading external resources like css, jquery file and other external file like in my case there were css, jquery, bootstrap file, fonts, morris chart js and css etc. So if we will load all these files from local devices instead of an http url then it will make a big difference.

=&1=&. Now next thing to do is rewrite your all you links to your static resources to local relative URLs. For example if you have added any script reference on your page like this

<script src="https://www.edunyte.com/script.js" type="text/javascript"></script>

or

<script src="../script.js" type="text/javascript"></script>

then change it to like this

<script src="script.js" type="text/javascript"></script>

Here we have assumed that script.js file was on your website root and you have copied it directly in assets folder. If you used to place all js in one folder (may be scripts) and all css in other (may be styles) then you can copy this complete folder to your asset toot and us link in your page like this:

<script src="scripts/script.js" type="text/javascript"></script>

and

<link href="styles/style.css" rel="stylesheet" type="text/css" />

=&2=& Now after this we have to get the webpage content using http request. I normally use Volley StringRequest class for this. You can see code below to get HTML content of any webpage using Volley StringRequest:

  StringRequest strReq = new StringRequest(Request.Method.GET, String.format(Config.URL_DASHBOARD, apiKey, studentId),
            new Response.Listener<String>() {
       @Override
       public void onResponse(String response) {
           //You will get the page HTML in response string object
       }
   }, new Response.ErrorListener() {
       @Override
       public void onErrorResponse(VolleyError error) {
        //If anything goes wrong you can handle that here
       }
   }
  );
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq);

In above code you will notice that I have used MyApplication class and added my request in it. This is class which manages the request queue using Singleton architecture. You can get code of this class from here.

=&3=& Now comes the final step. In OnResponse method we will get the complete HTML string of page in response String object. This string we will us to load webview by making file:///android_asset/ as root of the page. There is a method loadDataWithBaseURL which gives us option to set page root, specify HTML string to load along with specifying encoding etc. Se below

myWebView.loadDataWithBaseURL("file:///android_asset/", response, "text/html", "utf-8", null);

Now as soon as we call loadDataWithBaseURL method your html string content will load in webview and all the external static content you have used in the page will be loaded from assets folder of your app (provided that you have already copied these resource in assets folder and used proper linking on the page).

That’s all from my side for this article. Please write in comments section below if you any question or facing any problem.

Show Splash Screen While Android WebView is Loading

In one of my recent application (which was a webview app) my client suggested to show splash screen while we are loading the application data (obviously client does not bother if this is webview app or native one) so here I am with a sample for all those who are in similar situation.

I am not going to explain all the basic things like create project and activity etc as we have already discussed this in my previous articles.

1. First thing we have to do is create layout for our webview screen. We will name this layout file activity_main.xml. This file will contain webview element and splash screen element.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
 <RelativeLayout
     android:id="@+id/splach_screen"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:background="@drawable/splash_bg"
     android:visibility="visible" >
 
     <ImageView
         android:id="@+id/imgLogo"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_centerVertical="true"
         android:contentDescription="@string/splash_image_desc"
         android:src="@drawable/ic_logo" />
    
     <ProgressBar
      android:id="@+id/webViewProgress"
      android:layout_centerHorizontal="true"
      android:layout_centerVertical="true"
      android:layout_width="wrap_content"
         android:layout_height="wrap_content"
      android:layout_below="@+id/imgLogo" />
    
     <TextView
         android:id="@+id/error"
      android:layout_centerHorizontal="true"
      android:layout_centerVertical="true"
      android:layout_width="wrap_content"
         android:layout_height="wrap_content"
      android:layout_below="@+id/imgLogo"
         android:textColor="@color/loading_error"
         android:textSize="@dimen/loading_error"
         android:text="@string/loading_error"
      android:visibility="invisible"/>
    
     <Button
         android:id="@+id/reload"
      android:layout_centerHorizontal="true"
      android:layout_centerVertical="true"
      android:layout_width="wrap_content"
         android:layout_height="wrap_content"
      android:layout_below="@+id/error"
      android:text="@string/reload"
      android:onClick="reload"
      android:visibility="invisible" />
 
     <TextView
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:layout_marginBottom="10dp"
         android:textSize="12sp"
         android:textColor="#454545"
         android:gravity="center_horizontal"
         android:layout_alignParentBottom="true"
         android:text="@string/splash_loading_text" />
 </RelativeLayout>
 <LinearLayout
     android:id="@+id/main_view"
     android:orientation="vertical"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
    android:visibility="invisible">
     <WebView android:id="@+id/web_engine"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent" />
 </LinearLayout>
</LinearLayout>

In this layout we have one main layouts and two sub layouts. One of the two sub layouts contains our splash screen contents and other contains webview.

We have set splash screen layout to visible and webview layout to invisible which will be later changed when webview content is loaded.

2. Now we will create our application’s main activity. We will name it MainActivity.java and its code will be as below:

package com.edunyte.webviewsplashscreen;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {
@SuppressLint("SetJavaScriptEnabled")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

WebView myWebView = (WebView) findViewById(R.id.web_engine);

myWebView.setWebViewClient(new MyBrowser());
myWebView.clearCache(true);
myWebView.clearHistory();

myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setLoadsImagesAutomatically(true);
myWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
myWebView.loadUrl("https://edunyte.com/");
}

private class MyBrowser extends WebViewClient {
@Override
public void onPageFinished(WebView view, String url) {
if (findViewById(R.id.splach_screen).getVisibility() == View.VISIBLE) {
// show webview
findViewById(R.id.main_view).setVisibility(View.VISIBLE);
// hide splash screen
findViewById(R.id.splach_screen).setVisibility(View.GONE);
}
}
}
}

 

In this code we have loaded URL in webview and set webview client to handle onPageFilished event. onPageFinished event we will hide splash screen layout and show webview layout.

Apart from these two file you may need to add few more files like string.xml, style.xml, color.xml etc.

For complete code of this sample click here to download.