GPS in Android as a Library Module Published on Jitpack via Github. Part 2

Benson Kuria Macharia
23.12.2021
|
3363
GPS in Android as a Library Module

Test the Module, Connect the Project to GitHub, Publish the Library, and Test the Published Library

Test the Library from the App

To test the application library, add the package to the Gradle app dependencies. Sync the project after adding the dependency.

implementation project(":gpslibrary")

Create the Test Implementation in Main App

Add the Button to the 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"
    tools:context=".MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="0dp"
        android:layout_height="45dp"
        android:layout_margin="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn_gps"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        android:background="@color/design_default_color_primary"
        android:text="GPS"
        android:textColor="@color/common_google_signin_btn_text_dark_default"
        android:textSize="16sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="32dp"
        android:text="Click to Test GPS"
        android:textColor="@color/design_default_color_primary"
        android:textSize="16sp"
        app:layout_constraintBottom_toTopOf="@+id/btn_gps"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</android.support.constraint.ConstraintLayout>

Calling the test library from the MainActivity.java

package com.library.gpslocation;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.library.gps.GPS;

import java.util.ArrayList;
import java.util.List;

import static android.Manifest.permission.ACCESS_FINE_LOCATION;

public class MainActivity extends AppCompatActivity {
    private final static int REQUEST_ID_MULTIPLE_PERMISSIONS = 0x2;
    private static final int PERMISSION_REQUEST_CODE = 200;

    Context context;
    LocationManager locationManager;
    Button gpsBtn;
    GPS gps;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        gpsBtn=(Button) findViewById(R.id.btn_gps);

        gps=new GPS(MainActivity.this);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        context = getApplicationContext();
        checkPermissions();

        Button gpsBtn=(Button) findViewById(R.id.btn_gps);

        gpsBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkPermissions();
                if (permissionAlreadyGranted()) {
                    gps.show();
                }else{
                    requestPermission();
                }

            }
        });
    }

    @Override
    public void onBackPressed() {
        if(gps.isShown()){
            gps.dismiss();
        }else{
        }
    }

    private void checkPermissions(){
        int permissionLocation = ContextCompat.checkSelfPermission(MainActivity.this,
                ACCESS_FINE_LOCATION);
        List<String> listPermissionsNeeded = new ArrayList<>();
        if (permissionLocation != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(ACCESS_FINE_LOCATION);
            if (!listPermissionsNeeded.isEmpty()) {
                ActivityCompat.requestPermissions(this,
                        listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
            }
        }else{
        }
    }

    private boolean permissionAlreadyGranted() {
        int result = ContextCompat.checkSelfPermission(getApplicationContext(), ACCESS_FINE_LOCATION);
        return result == PackageManager.PERMISSION_GRANTED ;
    }

    private void requestPermission() {

        ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION, }, PERMISSION_REQUEST_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0) {
                    boolean locationAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    boolean callAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;

                    if (locationAccepted && callAccepted){
                    }
                } else {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (shouldShowRequestPermissionRationale(ACCESS_FINE_LOCATION)) {
                            showMessageOKCancel("You need to allow access to both the permissions in order to use address features",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                                requestPermissions(new String[]{ACCESS_FINE_LOCATION},
                                                        PERMISSION_REQUEST_CODE);
                                            }
                                        }
                                    });
                            return;
                        }
                    }
                }
                break;
        }
    }
    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(MainActivity.this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    }
}

Install the App

Install the App on your Android device and launch the app. If location access is not enabled, ensure you enable it before launching the app. Click on the button labeled ‘GPS’ and a dialog should appear. Click on the ‘START’ button and wait for a few seconds. The app should start displaying the latitude and longitudes of your current location.

Connecting an Android Project to GitHub

  • If you do not have a GitHub account yet, create it here. If you have one, open the browser and login into your account.
  • The second step is to install Git on your computer. Follow this link to download and install it. 
  • The third step is to enable Version Control on android studio. We do this by going to:
  • Menu->VCS->Enable Version Control Integration

Connecting an Android Project to GitHub

After enabling it, select Git as your VCS

Connecting an Android Project to GitHub 2

Once complete, you’ll note that all the files will turn red.

  • Create a GitHub repository and select the project
    Follow these steps: Go to VCS->Import into Version Control->Share Project on GitHub

    Name the repository and add a description for ease of identification. 

  • If no selection is done by default, select the library module and the Gradle Scripts. If the whole project has been selected, unselect the ‘app’ module and push the project. After this is complete, there should be a folder in your GitHub account containing the project. Open the browser and confirm the project is uploaded successfully before proceeding to the next step.
  • You can edit the code that has been uploaded by committing and pushing updates using VCS. It is important to add commit notes so that you can always track your updates.

Publishing the Library

Open the internet browser and go to the GitHub account containing the project created in the previous step.

Create a Release

Click on the project that was uploaded and confirm that the library module is available. Click on ‘Releases’ option to create a release that will be published. 

Fill in the release details; the tag and the description. The tag will be the unique identifier of the release and its subsequent upgrades. In our case, I would suggest the tag ‘1.0.0’ because it is the first version. Give the release your preferred name and add a release description. 

Create a Release

 

Click on ‘Create Release’ after you’ve added all the details.

Copy the release link that is provided under the ‘Code’ menu.

Copy the release link

Creating a Library Link in JitPack

Open the JitPack website here. Look up the release from JitPack using the link copied earlier. 

Creating a Library Link in JitPack

After clicking on lookup, you should now see your release appear below the search bar.

Now the library module is online and can be deployed into an app.

Creating a Library Link in JitPack 2

Test the Library in an App

  • Create an Android App
    Open Android Studio and start a new project. Select ‘Empty Activity’ and click on finish.

  • Add JitPack to the root build.gradle.
allprojects {
     repositories {
            ...
            maven { url 'https://jitpack.io' }
     }
}
  • Add the library dependency that is in JitPack to the project and Synch the project
dependencies {
	        implementation 'com.GitHub.KuriaMacharia:GPSLocation:1.0.0'
	}
  • Rebuild and install the project. Test the project after launch. If it has been successfully pushed and published, it should open a dialog just like in the first build.

Conclusion

In conclusion, published libraries are easy to integrate into existing apps and it is also a good way for developers to store implementations they reuse regularly. This article has focused on creating GPS as a dialog and then publishing it as a library. This is a tool that can be very useful if you want to offer your application as an API accessed through a library module. 

Happy coding!

You can find the project here: https://github.com/KuriaMacharia/GPSLocation.git

More stories

CSS or Cascade Sheet Styling in website designing
Building Blocks of CSS-Inheritance, Cascading, and Specificity

Define some of the initial concepts and building blocks of CSS. Understanding these basic concepts of CSS are fundamental for understanding more complex concepts in web designing.

Read more
implementation of MATLAB to C/C++ conversion and MEX-functions and simulation method Monte Carlo
MATLAB TO C/C++ Part2

Dive into the Monte Carlo simulation method. Read about specific circumstances for convenient implementation, real implementation of MEX-functions simulated by MATLAB.

Read more
create a GPS library model in android
GPS in Android as a Library Module Published on Jitpack via Github. Part 1

How to create a GPS library model in android and add Java class to implement GPS.

Read more
translation of MATLAB algorithms to C++ via the MEX-function
From MATLAB to C/C++ Part 1

Look at some of the benefits and disadvantages of using MATLAB, the difference between a compiler and interpreter and how to use a MEX-function within the MATLAB environment to automatically translate algorithms.

Read more
The Best Python Libraries for Deep Learning

5 best Python libraries for deep learning

Read more
some basics of adding interactivity to a webpage using JavaScript.
Introduction to JS Browser Events for Web Designers

Learn some basics of adding interactivity to a webpage using JavaScript. A new web designer or anyone wanting to revise the basics of JS browser events will find this article helpful.

Read more

Algo uses cookies for personalization and other purposes. Learn more about cookies use. Algo supports the Digital Advertising Alliance principles. By interacting with this site, you agree to our use of cookies.