How to create aar file for Ionic Project – Part 2

So the hardest part is what??? It’s the fact that your CordovaActivity inside the aar can’t be invoked from the client app. So, this tutorial isn’t complete until we are able to call CordovaActivity from outside the aar.

I am not going to spend time showing you that it can’t be invoked. But instead I’ll show you how to rewrite the CordovaActivity to Activity class.

If you notice the MainActivity.java in src>main>java>io>ionic>starter, the MainActivity class implements the CordovaActivity class.

To resolve this simply copy paste my Activity class below and paste it to replace your MainActivity.java:-

 
 
 package io.ionic.starter;
 
 
 import android.app.ActivityManager;
 import android.app.ActivityOptions;
 import android.app.AlertDialog;
 import android.os.Bundle;
 import org.apache.cordova.*;
 import android.app.Activity;
 import android.content.Context;
 import android.view.ViewGroup;
 import android.graphics.Color;
 
 
 import android.content.Intent;
 import java.util.ArrayList;
 import java.util.Locale;
 import android.media.AudioManager;
 import android.widget.FrameLayout;
 import android.net.Uri;
 import android.webkit.WebSettings;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.CompletableFuture;
 import org.json.JSONObject;
 import android.os.AsyncTask;
 
 
 public class MainActivity extends Activity
 {
 
 
 
 
     protected CordovaPreferences preferences;
     protected CordovaWebView appView;
     protected String launchUrl;
     protected ArrayList<PluginEntry> pluginEntries;
     protected CordovaInterfaceImpl cordovaInterface;
     public static String screenRender = "/details";
     private static Context context;
 
 
 
 
     public boolean setScreenRender(String screenname) {
         screenRender = screenname;
         return true;
     }
 
 
     @Override
     public void onCreate(Bundle savedInstanceState)
     {
         super.onCreate(savedInstanceState);
 
 
         // enable Cordova apps to be started in the background
         Bundle extras = getIntent().getExtras();
         if (extras != null) {
             this.screenRender=extras.getString("KEY");
             System.out.println("KEY:::::" + extras.getString("KEY"));
         }
 

         this.loadConfig();
         String logLevel = preferences.getString("loglevel", "ERROR");
         cordovaInterface = makeCordovaInterface();
         if (savedInstanceState != null) {
             cordovaInterface.restoreInstanceState(savedInstanceState);
         }
 
         //to implement async call here for intent received
         System.out.println("Received intent to render:::::::" + screenRender);
 
 
         class mATask extends AsyncTask<String, String, String>
         {
 
             protected void onPreExecute() {
                 super.onPreExecute();
                 Bundle extras = getIntent().getExtras();
                 if (extras != null) {
                     screenRender=extras.getString("ROOT");
                     System.out.println("root:::::" + extras.getString("ROOT"));
                 }
             }
             @Override
             protected String doInBackground(String... params) {
                 //Enter code for fetching value from remote server
                 return null;
             }
             @Override
             protected void onPostExecute(String result) {
                 loadUrl(launchUrl);//Enter code for parsing and create list view
             }
         };
         new mATask().execute("","","");
         //CompletableFuture.supplyAsync(this::getIntentExtras)
         //        .thenAccept(loadUrl(launchUrl));

     }

 // Author: Kok Seng, Chua
 // here are all the implementations of CordovaActivity to run the loadUrl
 
     private void getIntentExtras(){
         Bundle extrasMsg = getIntent().getExtras();
         if (extrasMsg != null) {
             this.screenRender=extrasMsg.getString("ROOT");
             System.out.println("root:::::" + extrasMsg.getString("ROOT"));
         }
     }
 
 
     @SuppressWarnings("deprecation")
     protected void loadConfig() {
         ConfigXmlParser parser = new ConfigXmlParser();
         parser.parse(this);
         preferences = parser.getPreferences();
         preferences.setPreferencesBundle(getIntent().getExtras());
 
 
         launchUrl = parser.getLaunchUrl();
         pluginEntries = parser.getPluginEntries();
         //Config.parser = parser;
     }
 
 
     public void loadUrl(String url) {
         if (appView == null) {
             init();
         }
         appView.loadUrlIntoView(url, true);
     }
 
     protected void init() {
         appView = makeWebView();
         createViews();
         if (!appView.isInitialized()) {
             System.out.println(pluginEntries);
             try {appView.init(cordovaInterface, pluginEntries, preferences);}
             catch (Exception e){}
         }
         cordovaInterface.onCordovaInit(appView.getPluginManager());
 
 
         // Wire the hardware volume controls to control media if desired.
         String volumePref = preferences.getString("DefaultVolumeStream", "");
         if ("media".equals(volumePref.toLowerCase(Locale.ENGLISH))) {
             setVolumeControlStream(AudioManager.STREAM_MUSIC);
         }
     }
 
 
     protected CordovaWebView makeWebView() {
         return new CordovaWebViewImpl(makeWebViewEngine());
     }
 
 
     protected CordovaWebViewEngine makeWebViewEngine() {
         return CordovaWebViewImpl.createEngine(this, preferences);
     }
 
 
     @SuppressWarnings({"deprecation", "ResourceType"})
     protected void createViews() {
         
         appView.getView().setId(100);
         appView.getView().setLayoutParams(new FrameLayout.LayoutParams(
                 ViewGroup.LayoutParams.MATCH_PARENT,
                 ViewGroup.LayoutParams.MATCH_PARENT));
 
         setContentView(appView.getView());
 
         if (preferences.contains("BackgroundColor")) {
             try {
                 int backgroundColor = preferences.getInteger("BackgroundColor", Color.BLUE);
                 // Background of activity:
                 appView.getView().setBackgroundColor(backgroundColor);
             }
             catch (NumberFormatException e){
                 e.printStackTrace();
             }
         }
 
         appView.getView().requestFocusFromTouch();
     }
 
     protected CordovaInterfaceImpl makeCordovaInterface() {
         return new CordovaInterfaceImpl(this) {
             @Override
             public Object onMessage(String id, Object data) {
                 // Plumb this to CordovaActivity.onMessage for backwards compatibility
                 //return KokSengActivityHandler.this.onMessage(id, data);
                 return super.onMessage(id,data);
             }
         };
     }
 
 
 }
 

There you have it….now make your module…

And as promised you can call your application from another app. Simply go to build>output>aar and copy the aar file.

Create your new client app and add the aar file to your client app’s libs folder. If it doesn’t have one yet, create a “libs” folder under app directory. To invoke the activity simply paste the following in your new client app:-

Intent intent = intent = new Intent(this, io.ionic.starter.MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(intent);

There it is Part 2 completed….if you run your client app, it should start the ionic screens you have created in Part 1.

Original tutorial by KS Chua. Thanks for learning with me.

How to create aar for Ionic project – Part 1

I am currently working on a mobile app project and I face a challenge of invoking Cordova Activity after I convert my project to aar library.  This is part 1 of the tutorial to convert Ionic 4 project to an invocable Activity in aar library. This is introduction for beginners. For advanced code-masters, go to part 2 and copy the code away….

Part 1:  Converting an Ionic project to an aar file (The easy part)

Prerequisite:

  • installed npm to install the following….
  • installed Ionic 4
  • installed Android Studio

Step 1: Create an ionic project

Install ionic using npm and create ionic project using the following command:

ionic start KSTutorial

Select whatever options you want…..there it’s that easy to create your ionic project. To see your creation use the following command:

cd KSTutorial

ionic serve

There you go…..an ionic page with oyster and stuff (oyster???? you will get this if you follow my tutorial)

Step 2: Open ionic cordova project in Android Studio

  1. Do the following command

ionic cordova build platform android

  1. Go into platform folder KSTutorial>platform, and copy the android folder
  2. Paste it somewhere and start up Android Studio
  3. Then in Android Studio select open project and open the android folder where you pasted just now.
  4. There you have an Android project. But wait, what are these errors????
  5. You will have to open Manifests files found under app and Cordova folders to remove the whole tag <uses-sdk>

<uses-sdk …. />

just remove the second last line in the xml file. If you can’t find the manifest files, it is under the app>src>main folder (In Project View) and CordovaLib>src>main folder

  1. Then select Run>Rebuild Project
  2. And there you have it – ionic converted to Android Studio project. Phew….that was too easy… 🙂

Step 3: Create an aar file

What is an aar file? It is the extension used for android module that can be used as a library of resources and classes that can be invoked from another Android project. This is my short and uneducated explanation – don’t copy in your theses and blame me…..

So to create an aar file it’s just a few more steps.

Open your app build.gradle file. If you don’t know where it is, google….no kidding. It is in the app folder under project view. If you are new to Android Studio, there are several views to look at your project structure. Just click on the Android word on top right of the directory tree and change to Project. See I am nice to tell you instead of Googling it away…..

  1. Change the top line from android.application to android.library in build.gradle  for the app folder
  2. That’s it. Now select Build> Make module app and in the build>output folder, you will see the aar file.

Done! As easy as whatever….not a single line of code.

Wait you, until part 2…you will copy paste all those codes away instead of writing a single line…..

No codes for this part cause it’s too easy peasy. In part 2, I’ll provide the source for you.

Blockchain tutorial -part 2 (Blockchain on Grails)

I did a blockchain on grails example to learn up Grails. Excuse the poor UI as this is my first time doing Grails. It will allow to store document hash reviewed and review comments on blockchain and able to retrieve the details from your blockchain using the get details page in Grails even after it’s been deleted. Run it and have fun.

Download the pack here.

Steps to install:-

1. Install grails and geth on windows from https://ethereum.github.io/go-ethereum/downloads/ and http://docs.grails.org/latest/guide/gettingStarted.html#requirements

2. Unpack my zip file.
3. Run your node. Go to bcnetwork folder in the unzipped folders and run geth using command :

geth –rpc console –datadir “miner2” –networkid 55555 –rpcaddr “localhost” –rpccorsdomain “*” -rpcport 22000 –rpcapi “web3,net,personal,eth” attach
4. Start miner in console by running:
miner.start()
5. Run grails. Open another terminal. Change folder to BCReview and run grails app.

cd BCReview
grails run-app

6. Open http://localhost:8080
7. Have fun with your reviews.

Blockchain tutorial -part 1 (Smart Contract)

This is based on the great tutorial from Manuel Araoz at https://blog.zeppelin.solutions/the-hitchhikers-guide-to-smart-contracts-in-ethereum-848f08001f05

It is implemented to check uploaded file and maintain the proof of the file content by storing hash key of the file content in blockchain. Unpack testpack.zip in your Ubuntu to play around with it.

To install and see the tutorial pack:-

On Windows:-

Install chocolatey
Run command prompt as administrator and run following commands:
choco install git
choco install golang
choco install mingw

set “GOPATH=%USERPROFILE%”
set “Path=%USERPROFILE%\bin;%Path%”
setx GOPATH “%GOPATH%”
setx Path “%Path%”
mkdir src\github.com\ethereum
git clone https://github.com/ethereum/go-ethereum src\github.com\ethereum\go-ethereum
cd src\github.com\ethereum\go-ethereum
go get -u -v golang.org/x/net/context

install -v ./cmd/…
On Linux/Ubuntu:-
install the following:

sudo npm install -g geth
sudo apt-get install solc
sudo apt-get install Node.js
sudo npm install web3
1. Unzip testpack to a test directory
change directory to the unzipped directory

2. Run the following commands:-
geth –rpc console –datadir “miner1” –networkid 55555 –rpcaddr “127.0.0.1” -rpcport 22000 –rpcapi “web3,net,personal,eth” –rpccorsdomain “*” attach

3. Then in the console unlock the account:-
web3.personal.unlockAccount(web3.personal.listAccounts[0],”escf1f2f3″, 0)

4. Then in console:-
miner.start()

5. Next open up ./testpack/check/index.html
Check any file you want, it should display false.

6. Open up ./testpack/upload/index.html
Upload any file and wait, it should display transaction to uploaded file

7. Wait for it to commit to mine for a few minutes, then use check/index.html to check for file uploaded is true file.

The program uses blockchain contract to check proof of existence of an uploaded file by storing it’s hash. Once stored it will remain in the contract to check whether it is the real file.