Android, Codes and Tips

Just in

3/17/2019

How to convert a Website to an android application with API 28 and Push Notification

How to convert a Website to an android application with API 28 and Push Notification
 

How to convert Website to android app with API 28 and Push Notification

We are going to add these codes one by one to android studio so convert website to an android application. 

 Ensure you read How to change website to android application

Note: Check below the post to know what to replace in read letters. all the words in red colour inside the codes will be edited.

How to convert a Website to an android application 2109


  1. Use Laptop or desktop of appreciable speed and large HDD.

  2. A data of least 8GB with a network of higher speed.

  3. Download Android Studio latest version.

  4. Prepare Splash Image(optional) and android logo image.

  5. Download AVD for virtual image display.
    Note:  Or use android phone 8.0 or 9.0 version.

  6. Go to firebase.com and create messaging project.


 

1. Go to App >> Java >> *Package Name >> MainActivity.Java



package com.domain.domain;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.graphics.Bitmap;
import android.view.View;
import android.webkit.WebChromeClient;
import android.widget.Toast;

import com.google.firebase.messaging.FirebaseMessaging;



public class MainActivity extends AppCompatActivity {

    String websiteURL = "https://*google.com"; // sets web url
    private WebView webview;
    SwipeRefreshLayout mySwipeRefreshLayout;
    private ProgressBar progressBar;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        //This sets the webview URL from push notifications.
        if(getIntent().getExtras() != null){
            for(String key: getIntent().getExtras().keySet()){
                if(key.equals(("url"))){
                    websiteURL = getIntent().getExtras().getString(key);
                }
            }
        }

        if( ! CheckNetwork.isInternetAvailable(this)) //returns true if internet available
        {
            //if there is no internet do this
            //setContentView(R.layout.activity_main);

            new AlertDialog.Builder(this) //alert the person knowing they are about to close
                    .setTitle("You need an internet connection to use this app")
                    .setMessage("Check to see if you're mobile data is on or you are connected to a wi-fi network.")
                    .setPositiveButton("Okay", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    //.setNegativeButton("No", null)
                    .show();
        }
            else
        {
            //Webview stuff
            webview = findViewById(R.id.webView);
            webview.getSettings().setJavaScriptEnabled(true);
            webview.getSettings().setDomStorageEnabled(true);
            webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
            webview.loadUrl(websiteURL);
            webview.setWebViewClient(new WebViewClientDemo());
            webview.setWebChromeClient(new WebChromeClientDemo());
        }

        //Swipe to refresh functionality
        mySwipeRefreshLayout = this.findViewById(R.id.swipeContainer);

        mySwipeRefreshLayout.setOnRefreshListener(
            new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    webview.reload();
                }
            }
        );

        //Progress bar variables
        progressBar = findViewById(R.id.progressBar);
        progressBar.setMax(100);
    }


    private class WebViewClientDemo extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            progressBar.setVisibility(View.GONE);
            progressBar.setProgress(100);
            mySwipeRefreshLayout.setRefreshing(false);
        }
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            progressBar.setVisibility(View.VISIBLE);
            progressBar.setProgress(0);
        }

    }
    private class WebChromeClientDemo extends WebChromeClient {
        public void onProgressChanged(WebView view, int progress) {
            progressBar.setProgress(progress);
        }
    }


    //set back button functionality
    @Override
    public void onBackPressed() { //if user presses the back button do this
        if (webview.isFocused() && webview.canGoBack()) { //check if in webview and the user can go back
            webview.goBack(); //go back in webview
        } else { //do this if the webview cannot go back any further

            new AlertDialog.Builder(this) //alert the person knowing they are about to close
            .setTitle("You are about to close the application")
            .setMessage("You cannot go back any further, would you like to close?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            })
            .setNegativeButton("No", null)
            .show();
        }
    }
}

class CheckNetwork {
    private static final String TAG = CheckNetwork.class.getSimpleName();
    public static boolean isInternetAvailable(Context context)
    {
        NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info == null)
        {
            Log.d(TAG,"no internet connection");
            return false;
        }
        else
        {
            if(info.isConnected())
            {
                Log.d(TAG," internet connection available...");
                return true;
            }
            else
            {
                Log.d(TAG," internet connection");
                return true;
            }
        }
    }
}




2. Go to App > >Manifests > >AndroidManifest.Xml




<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.domain.domain">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.Launcher">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".MyFireBaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"></action>
            </intent-filter>
        </service>
        <service android:name=".MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"></action>
            </intent-filter>
        </service>
    </application>

</manifest>




3. Go to App >> Res > >Layout >> Activity_main.Xml



<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/main_container"
    tools:context=".MainActivity">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipeContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <WebView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/webView"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />

    </android.support.v4.widget.SwipeRefreshLayout>


    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="10dp"
        android:layout_alignParentTop="true"
        android:background="@color/colorPrimaryDark"
        android:max="100"
        android:progress="20"
        android:indeterminate="false"
        android:progressTint="@color/colorAccent" />


</android.support.constraint.ConstraintLayout>


Watch Firebase push button notification configuration here.




4.  Go to App >> Res > >Drawable Right Click >> New >> Drawable Resource File >> add launch_screen. Check *Splash Image




<?xml version="1.0" encoding="utf-8"?>

<!-- The android:opacity=”opaque” line — this is critical in preventing a flash of black as your theme transitions. -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" android:opacity="opaque">
    <item android:drawable="@color/colorPrimaryDark"/>

    <item>

        <bitmap
            android:src="@drawable/logo"
            android:gravity="center"/>
    </item>


</layer-list>


5. Go to App > >Res >> Valus >> Styles.Xml and add

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

        <item name="android:windowBackground">@drawable/launch_screen</item>

    </style>

    <style name="AppTheme.Launcher">
        <item name="android:windowBackground">@drawable/launch_screen</item>
    </style>

</resources>



6. App > Res > Valus > Colors.Xml

The in thing you do here is to change the HTML colour codes to suit you. You can watch the video here.


7. Go to App >> Res >> Right Click > New > Image Asset


You use this to change your android application icon or log image.


Introdction of Push Notification message services. Go www.firebase.com and create a new/add a new project. Download the project jason file and add to your Share explorer>>App>>App. Get details here

8. Go to Gradle Scripts >> Build.Gradle (Project) and add



// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
   
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.0'
        classpath 'com.google.gms:google-services:4.0.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


9. Go to  Gradle Scripts >> Build.Gradle (Module:app) and add


apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.domain.domain"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.firebase:firebase-core:16.0.1'
    implementation 'com.google.firebase:firebase-messaging:17.3.3'

}
apply plugin: 'com.google.gms.google-services'




10. Go toApp >> Java >> Package Name Right Click > New > Java Class > Name It MyFireBaseInstanceIDService



package com.domain.domain;

import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

public class MyFireBaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String REG_TOKEN = "REG_TOKEN";
    @Override
    public void onTokenRefresh() {
        String recent_token = FirebaseInstanceId.getInstance().getToken();

        Log.d(REG_TOKEN,recent_token);
    }
}




11. Go to  App > >Java >> Package Name Right Click > New > Java Class > Name It MyFireBaseMessagingService



package com.domain.domain;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import java.util.Map;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Intent intent = new Intent(this, MainActivity.class);
        Log.d("Firebase Message", "Message Received Loud And Clear!");

        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
        notificationBuilder.setContentTitle("FCM NOTIFICATION");
        notificationBuilder.setContentText(remoteMessage.getNotification().getBody());
        notificationBuilder.setAutoCancel(true);
        notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
        notificationBuilder.setContentIntent(pendingIntent);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0,notificationBuilder.build());

        //Change URL section
        String url = remoteMessage.getData().get("url");
        intent.putExtra("url",url);
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
        localBroadcastManager.sendBroadcast(intent);

    }
}



done thanks

Change *google.com to your blog name

 Change *Package Name to your application name

Change @string/app_name to your application name like TechMax.

Change domain.domain to My application name created here. 

In No4 you must add your Splash Image named logo(png format) into drawable folder.

Convert your image to mpp format here

We have converted about 100 websites to responsive android applications. If you want us to convert yours use our email address or comment section.

How to convert a website to an Android app Part 1 and How to convert a website to an Android app Part 2.
 

No comments:

Post a Comment