Opening Orga App through Intent in Open Event Android App

In the Open Event Android App there is a section called “Manage events”, we direct the users to the Organizer’s app if the users have the app already installed otherwise we open the organizer’s app in the playstore. This way users are motivated to create events using the organizer’s app. Let’s see how this feature was implemented.

So when the user clicks on the menu item “Manage Events” startOrgaApp function is called with the package name of the organizer’s app as the argument. Android apps are uniquely identified by their package names in the playstore.

override fun onOptionsItemSelected(item: MenuItem?): Boolean {

when (item?.getItemId()) {
R.id.orgaApp -> {
startOrgaApp("org.fossasia.eventyay")
return true
}
}

 

Let’s have a look at the startOrgaApp function that we are calling above. We are using a try/catch block here. We are opening the app in the try block if it is installed otherwise we throw ActivityNotFoundException and if this exception happens we will catch it and use the showInMarket function to show the Organizer’s app in the market.

private fun startOrgaApp(packageName: String) {
val manager = activity?.packageManager
try {
val intent = manager?.getLaunchIntentForPackage(packageName)
?: throw ActivityNotFoundException()
intent.addCategory(Intent.CATEGORY_LAUNCHER)
startActivity(intent)
} catch (e: ActivityNotFoundException) {
showInMarket(packageName)
}
}

 

Now since we know this will never raise an exception there is no try catch block as the app with this package name will always be there. We just need to create an intent with the required parameters and then just pass the intent to startActivity

private fun showInMarket(packageName: String) {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$packageName"))
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
}

 

Lastly we just need to add the XML code to create a menu item. It should contain the id so that we can reference it and the title that will be visible.

<group android:id="@+id/profileMenu">
<item
android:id="@+id/orgaApp"
android:title="@string/manage_events" />
</group>

 

That’s it now you can open an app in the playstore if it is not installed or just open the app if the user has already installed the app.  

Resources

  1. Vogella Intent tutorial – http://www.vogella.com/tutorials/AndroidIntent/article.html
  2. Official Android Documentation Intent – https://developer.android.com/guide/components/intents-filters
  3. Javatpoint intent tutorial – https://www.javatpoint.com/android-explicit-intent-example
Continue ReadingOpening Orga App through Intent in Open Event Android App

Implementing search bar in PSLab app

PSLab offers a large range of functions with a large field of applications. This results in the long access path to certain information and functionality in the app, which affects the user experience (UX) negatively. In this blog post, I will show how the UX in Android applications with many functions can be improved by implementing a ‘Search Bar’. Further, I have created a screencast that follows the step-by-step description shown in this blog post [1].

Search Bar is the functionality which can be seen nowadays in almost all the apps. It is a handy widget for users to navigate the app. PSLab’s Android app was lacking this functionality and so I added it using an external library from Mirrajabi called ‘search-dialog’ [3]. I decided to use this library as it provides a search bar with built-in functionality of highlighting the text that’s selected or written down in the ‘Edit Text’ field by the user and also it overlays on the screen which provides a good user experience rather than other search bars which overlap on the text provided on the screen with a ListView. Further working with this dependency was easier than working with others as it seems well designed.

The Search Bar was added in the Saved Experiments section which contains a lot of default experiments along with their respective manuals. The search bar was intended to provide the user with a greater UI so that they don’t need to navigate through sections every time to find an experiment.

This blog is a step by step guide on how to implement it in any app.

  1. First, add dependencies in the gradle at both project level and app level. By adding these dependencies, we don’t need to worry about writing code for how the Search Bar will filter searches and how it will be placed on the screen.

App Level :

'com.github.mirrajabi:search-dialog:1.1'

Project Level :

maven { url "https://jitpack.io" }
  1.  Create a SearchModel class which will help to carry out the search operations.
public class SearchModel implements Searchable {

	private String mTitle;

	public SearchModel(String mTitle) {
    	this.mTitle = mTitle;
	}

	public void setTitle(String mTitle) {
    	this.mTitle = mTitle;
	}

	@Override
	public String getTitle() {
    	return mTitle;
	}
}

The SearchModel class helps to communicate with the filtered search results by returning the string which is selected:

  • SearchModel(String string) – It is a default constructor
  • setTitle(String string) – It is a method used to set the string provided in the search results
  • getTitle() – It is also a method to get the string selected by the user from the filtered search result provided
  1.  Now provide some data which needs to be searched using an ArrayList or by using StringArrays and then converting it to Search Model Object.
private ArrayList<SampleSearchModel> createSampleData(){
        ArrayList<SampleSearchModel> items = new ArrayList<>();
        items.add(new SampleSearchModel("First item"));
        items.add(new SampleSearchModel("Second item"));
        items.add(new SampleSearchModel("Third item"));
        items.add(new SampleSearchModel("Fourth item"));

        return items;
    }
  1.  At last add the constructor in MainActivity to make the search bar.
SimpleSearchDialogCompat(Context context, String title, String searchHint, @Nullable Filter filter, ArrayList<T> items,
SearchResultListener<T> searchResultListener)

All the parameters can be given according to requirement. The function of each and every parameter are as under :

  • Context – Provide context of the current activity
  • String title – To provide title to Search Bar
  • String searchHint – To provide hint text to the user
  • Filter – To provide any additional filters to the search made by the user
  • ArrayList<T> – To provide data that can be searched
  • SearchResultListener<T> – The method which handles what to do when a user clicks on the filtered searches provided

Let’s try to search for the Piezo Buzzer and UltraSonic Range Finder Experiments in the Search Bar :

Figure 1. GIF of implemented Search Bar

So, in this way, I have implemented the Search Bar functionality in the PSLab application. One last note that try to practice this widget before implementing it in the main project as it requires some practice of filters as per requirements and also its location needs to be defined as per the requirement of an organization as it can be placed anywhere from the main screen to the toolbar to navigation drawer. Below are some of the useful resources to get best practice.

Resources

  1. https://youtu.be/QyqbRHt1NUE – How to make a search bar like above (By – Harsh Patel (me))
  2. https://github.com/mirrajabi/search-dialog – This is the GitHub Page of the library which I used in making an attractive screen overlaying search bar rather than the old one with the list view placed in the toolbar
Continue ReadingImplementing search bar in PSLab app

Creating the onScreen Monitor Using CardView

The PSLab works as a Wave generator and the Oscilloscope when connected with the Android device. The mockup of the Wave Generator has been created in the blog Creating the Mockup for Wave Generator using Moqups.

In this blog, we will create the monitor screen in the PSLab Android app using Android studio.

Deciding the layout to use for monitors

As monitors with rounded border look appealing on android device screen so we will select CardView to be the base layout of our monitors. The CardView element allows us to add certain properties like rounded corners, elevation etc.

To use the CardView in your app, add the following dependency to build.gradle file and sync the project.

dependencies {    // CardView    
implementation 'com.android.support:cardview-v7:27.1.1'
}

Add the <android.support.v7.widget.CardView> widget to your layout and all the other views to be shown on monitor screen will be placed inside this card layout as its child layout.

Creating the monitor cards

We need to decide how much spacing is to be provided to the cards to properly view them on different screens. Here we make use of the special attribute in the View class.

android:layout_weight=1

This attribute assigns an “importance” value to a View in terms of how much space it should occupy on the screen. That is if we give equal weight to two views which inside the same parent then they will both occupy equal space.

To implement this create two CardViews inside <LinearLayout> with the same layout_weight.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:layout_width="0dp"
        android:layout_height="250dp"
        android:layout_weight="1"
        card_view:cardCornerRadius="10dp" />

    <android.support.v7.widget.CardView
        android:layout_width="0dp"
        android:layout_height="250dp"
        android:layout_weight="1"
        card_view:cardCornerRadius="10dp" />

</LinearLayout>

So this will give us a screen like this with equally weighted monitor card views as shown in Figure 1.

Figure 1 shows two CardView with equal weights(w/2) and equal width

Both the cards have the width equal to half the screen width which is set automatically by the Android.

Creating partitions in the monitors

We have to make partitions in the monitor screen so that every characteristic of Wave Generator like wave frequency, phase, selected pin etc. can be viewed simultaneously on the screen with proper spacing.

For making partitions we need to make a separator line which we can create by using <View> and setting the attributes as below:

<View
        android:layout_width="@dimen/length_0dp"
        android:layout_height="@dimen/divider_width"
        android:background="@color/dark_grey" />

This will create a thin line having the grey color. We have to make four partitions of the card view for both monitors as shown in Figure 2.

Figure 2 shows two monitors with line separator making partitions

Populating the screen with text and image icons

We have to include the <TextView> and <ImageView> to show the property data on the monitors.

Figure 3 shows partitions in the monitor CardView

Different partitions as shown in Figure 3 can be used for showing different data such as:

  1. Top Partition:- To view the selected wave. 
  2. Left Partition:- To view the selected waveform eg:- sine, triangular 
  3. Right Partition:- To view the selected wave characteristics like frequency, phase etc. 
  4. Bottom Partition:-  To view the property selected which has been selected by user

After inserting all the desired Views and providing the Views with dummy data and icons and customizing the Views by giving proper color and spacing finally we will have a layout as shown in Figure 4.

Figure 4 shows ImageView and TextView showing different dummy data

In Figure 4, the left CardView shows all the properties for the Analog Wave Generator and the right CardView shows all the properties for Digital Wave Generator.

All the characteristics on the monitors can be controlled by the controlling panel which is work in progress.

Resources:

  1. https://developer.android.com/guide/topics/ui/layout/cardview– Article on How to Create a card based layout by Android Developer Documentation 
  2. https://stackoverflow.com/questions/5049852/android-drawing-separator-divider-line-in-layout – Stack Overflow post to create separator line

 

 

Continue ReadingCreating the onScreen Monitor Using CardView

Displaying all the images from storage at once in Phimpme Android Application

In the Phimpme Android application, the images are displayed in the albums in which they are indexed in the device’s storage. However, there is also an “All photos” section in the application where all the images present in the device’s storage are displayed at once irrespective of the folder they’re indexed in. So in this post, I will be discussing how we achieved the “All Photos”  functionality.

Android framework provides developers with a media content provider class called MediaStore. It contains metadata for all available media on both internal and external storage devices. With the help of particular methods we can obtain metadata for all the images stored in the device’s storage.

Step 1

So First we need to get the Uri from MediaStore content provider pointing to the media(here media refers to the photos stored on the device). This can be done by the following snippet of code.

Uri uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

Step 2

Now retrieving a cursor object containing the data column for the image media is required to be performed. The data column will contain the path to the particular image files on the disk. This can be done by querying the MediaColumns table of the MediaStore class, which can be performed by the use of the content resolver query method. The mentioned functionality can be achieved by the following lines of code.

String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cursor = activity.getContentResolver().query(uri, projection, null, null, null);

Step 3

In the final step, we would retrieve the path of all the images by iterating through the cursor object obtained in the previous step and keep adding those paths to an ArrayList<String>. Creating Media objects passing in the image path and concurrently adding those Media objects to an ArrayList<Media> to be done thereafter. Finally, the dataset(ArrayList<Media> in this case) containing Media objects for all the images is required to be passed to the Media Adapter in order to display all the photos in the UI. The code snippets used for the final steps are provided below.

while (cursor.moveToNext()) {
  absolutePathOfImage = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA));
  listOfAllImages.add(absolutePathOfImage);
}
ArrayList<Media> list = new ArrayList<>();

for (String path : listOfAllImages) {
  list.add(new Media(new File(path)));
}
return list;

This is how we achieved the functionality to display all the images from the storage on a single screen(at once) in the Phimpme Android application. To get the full source code, please refer to the Phimpme Android Github repository listed in the resource section below.

The screenshot for displaying the “All photos” section is provided below.

Resources

1.Android Developer Guide – https://developer.android.com/reference/android/provider/MediaStore

2.Github-Phimpme Android Repository – https://github.com/fossasia/phimpme-android/

3.Displaying all the images from gallery in android – https://deepshikhapuri.wordpress.com/2017/03/20/get-all-images-from-gallery-in-android-programmatically/

Continue ReadingDisplaying all the images from storage at once in Phimpme Android Application

Creating the Mockup for Wave Generator using Moqups

PSLab is a versatile device that can be used as a waveform signal generator, as it is capable of producing different types of waves. It provides a cheap and portable alternative as compared to the physical wave generators available in markets.

The current UI of the Wave Generator present in the PSLab app as shown in Figure 1 is very basic and makes use of some basic UI components which are not able to properly expose all the functionalities of the wave generator. This affects the user experience negatively.

Figure 1 shows the current layout of Wave Generator in PSLab android app

In this blog, we will discuss creating a mockup for the PSLab wave generator using modern design to improve the UI/UX of the app. I will try to keep the layout simple enough so that users can easily understand it. 

Understanding the Functionality of Waveform Generator

Figure 2 shows the schematic pin diagram of the PSLab

We can observe from the image that PSLab provide:

  • Two pins named W1 and W2 which are capable of producing two different sine or saw-tooth waves having different characteristics simultaneously.
  • Four Pins named SQ1, SQ2, SQ3, SQ4 which are capable of producing Square Wave and Pulse Width modulation signals.
  • It also allows us to change the properties of these waves such as frequency, phase, duty cycle.

Before starting with the mockup a physical commodity Waveform Signal Generator as shown in Figure 3 was inspected.

Figure 3 shows digital Wave Generator by HP

Most waveform generators in the market have a control panel with buttons and a monitor screen so that the user can view the changes while controlling the characteristics of the wave. I will try to create a layout similar to this in following steps by dividing it into two halves:

  1. Upper half containing monitor screens
  2. Lower half containing controlling panel having buttons

Steps for creating the mockup

Step 1: Choosing the Tool

The tool that we will be using here to create a mockup is moqups[1].

I have chosen this software because:-

  • It is an online tool and doesn’t require it to be set up first
  • It is very efficient and powerful tool for creating mobile or web wireframes.
  • It doesn’t require any prior knowledge of programming language.
  • It has a palette to drag & drop UI elements like Buttons, Textboxes, Checkboxes etc. on the left-hand side, allows modifying the features of each element (here on the right) and other options at the top related to prototyping, previewing etc as shown in figure 4.
Figure 4  shows Moqups prototyping tool webpage

Step 2: Creating the base of the layout

The mockup tool moqups[1] have a built-in template of Android screen which we can drag and drop from the palette and use it as our base.

Figure 5 shows the Android mobile template picked from the palette of available design elements in the ‘moqups’ application.

Step 3: Creating the Lower Half

Now as discussed above I will create controlling panel containing buttons in the lower half of the screen, for this I will drag and drop buttons from the palette on the right-hand side and design them according to the theme of the app that is making their border round shape, changing their color to match the theme color and editing text in them. As the PSLab has two groups of pins so I will create two different panels with buttons for properties related to the pins of that group.

At this point we have a layout looking like this:

Figure 6 shows the lower panel containing buttons being drawn for Wave Generator UI. At right-hand side, it shows the palette having different UI elements.

I will create the monitor screens in the upper half, for our purpose as I have two panels we will create two monitor screen as shown in Figure 6. The left panel will correspond to the left panel and the right monitor will correspond to the right panel.

Step 4: Creating the Upper Half

For creating monitor, I will use simple rectangles with rounded borders and give the background black to resemble the monitor in physical devices.

I will also create some partitions in the monitor to make compartment. I will use these compartments to position the text view that represents the characteristics of the wave so that they are clearly visible.

Figure 7 shows two monitor layout with the black background being drawn using text areas and lines

So, in this layout the user will be able to see all the properties corresponding to one type of waveform on the monitor together so he/she doesn’t have to click the buttons, again and again, to see the different properties as he/she have to do in a physical device.

For instance let’s say, if the user wants to generate sine wave he/she will have to click the Wave 1 button in the panel below and on clicking,all the values of characteristics related to waveform produced by W1 pin will be visible together to the user in one screen which makes it easier for the user to analyze and set the values.

Therefore, the final layout produced is shown in Figure 7

Figure 8 shows final Wave Generator Mockup.

As we can see this layout is quite interactive and looks very appealing to the user and this will help to improve UI/UX of the app.

Resources

  1. Moqups prototyping tool website: https://moqups.com
  2. Youtube Video – How to use moqups
Continue ReadingCreating the Mockup for Wave Generator using Moqups

Use PreferenceManager in place of SharedPreferences

SharedPreferences is used in android to store data in the form of a key-value pair in an application. But, sometimes we need to store data at many places in the application such as saving the login email or a particular information that remains the same for the entire use of the app. In SUSI.AI android app PrefManager.java class is made that uses the sharedpreferences in android and provides a custom wrapper that is used to store the data in the key-value pair form in the app.

To store data in sharedpreferences through the PreferenceManager class we just need to declare an instance of the PreferenceManager in the location in which we want to save the data. The SUSI.AI Android app opens up the login screen and on just viewing the welcome cards for the first time due to the incorrect implementation of the sharedpreferences, using the Preference Manager we can correctly implement the preferences in welcome activity.

Whenever we install the SUSI.AI Android app, on opening it for the first time we see welcome cards that give a basic overview of the app. So, now after swiping all the cards and on reaching the final card instead of clicking GOT IT to move to the login screen and on pressing the home button we put the app in the background. Now, what happened was when the app showed cards, it was due to the WelcomeActivity.java activity.

In the onCreate() method of this activity we check whether the WelcomeActivity is opened for the first time or not. In this case we make use of the PrefManager.java class.

if (PrefManager.getBoolean(“activity_executed”, false)) {
  Intent intent = new Intent(this, LoginActivity.class);
  startActivity(intent);
  finish();
} else {
  PrefManager.putBoolean(“activity_executed”, true);
}

This piece of code calls the getBoolean(<preferenceKey>,<preferenceDefaultValue>) of the PrefManager.java class and checks the boolean value against the preference key passed in the function.

If it is the first time when this function is called then the default value is accessed against the preference key: “activity_executed”, which is passed as false and no code within the if statement is executed and so the code in the else block is executed which puts the value true as the preference value against the key “activity_executed” and the next line is executed in the sequence after this line. In short, on opening the app for the first time the preference key “activity_executed” has a value of true against it.

When we close the app by destroying it while it is in the WelcomeActivity, the onDestroy() method is called and memory is cleared, but when we open the app again we expect to see the Welcome Cards, but instead we find that we are on the login screen, even though the GOT IT button on the final card was not pressed. This is because when we go through the onCreate() method again the if condition is true this time and it sends the user directly to the Login activity.

To, solve this problem the method that was followed was :

  1. Remove the else condition in the if condition where we check the value stored against the key “activity_executed” key.
  2. In the onCreate() method of the LoginActivity.kt file use the PrefManager class to put a boolean value equal to true against the key : “activity_executed”.So the code added in the LoginActivity.kt file’s onCreate() method was :
PrefManager.putBoolean(“activity_executed”, true)

Also, the else condition was removed in the Welcome activity. Now, with these changes in place unless we click GOT IT on the final card in the welcome activity we won’t be able to go to the Login Activity, and since we won’t be able to go to the final activity the value against the key “activity_executed” will be false. Also, once we move to the login activity we will not be able to see the cards as the if condition described above will be true and the intent will fire the user to the Login Activity forever.

Therefore, using the PrefManager class it became very easy to put values or get values stored in the sharedpreferences in android. The methods are created in the Preference manager for different types corresponding to the different return types present that can be used to store the values allowed by the SharedPreferences in Android.

Using the PrefManager class functions it was made easy in SUSI.AI android app to access the SharedPreferences and using it a flaw in the auth flow and opening of the app was resolved.

 

Resources

  1. How to launch an activity only once for the first time! – Divya Jain:  https://androidwithdivya.wordpress.com/2017/02/14/how-to-launch-an-activity-only-once-for-the-first-time/
  2. Save key-value data : ttps://developer.android.com/training/data-storage/shared-preferences
  3. PrefManager Class: https://github.com/fossasia/susi_android/blob/development/app/src/main/java/org/fossasia/susi/ai/helper/PrefManager.java
Continue ReadingUse PreferenceManager in place of SharedPreferences

Chrome Custom Tabs Integration – SUSI.AI Android App

Earlier, we have seen the apps having external links that opens and navigates the user to the phone browser when clicked, then we came up with something called WebView for Android, but nowadays we have shifted to something called In-App browsers. The main drawback of the system/ phone browsers are they caused heavy transition. To overcome this drawback “Chrome Custom Tabs” were invented which allowed users to walk through the web content seamlessly.

SUSI.AI Android App earlier used the system browser to open any link present in the app.

This can be implemented easily by

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(browserIntent);

This lead to a huge transition between the context of the app and the web browser.

Then, to reduce all the clutter Chrome Custom tabs by Google was evolved which drastically increased the loading speed and the heavy context switch was also not taking place due to the integration and adaptability of custom tabs within the app.

Chrome custom tabs also are very secured like Chrome Browser and uses the same feature and give developers a more control on the custom actions, user interface within the app.

                                comparing the load time of the above mentioned techniques

Ref : Android Dev – Chrome Custom Tabs

Integration of Chrome Custom Tabs

  • Adding the dependency in build.gradle(app-level) in the project
dependencies {
    //Other dependencies 
    compile 'com.android.support:customtabs:23.4.0'
}
  • Now instantiating a CustomTabsIntent Builder

    String url = “https://www.fossasia.org” // can be any link
    
    CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(); //custom tabs intent builder
    
    CustomTabsIntent customTabsIntent = builder.build();
  • We can also add animation or customize the color of the toolbar or add action buttons.

    builder.setColor(Color.RED) //for setting the color of the toolbar 
    builder.setStartAnimations(this, R.anim.slide_in_right, R.anim.slide_out_left); //for start animation
    builder.setExitAnimations(this, R.anim.slide_in_left, R.anim.slide_out_right); //for exit animation
  • Finally, we have have achieved everything with a little code. Final launch the web page

    Uri webpage = Uri.parse(url); //We have to pass an URI
    
    customTabsIntent.launchUrl(context, webpage); //launching through custom tabs

Benefits of Chrome Custom Tabs

  1. UI Customization are easily available and can be implemented with very few lines of code. 
  2. Faster page loading and in-app access of the external link 
  3. Animations for start/exit  
  4. Has security and uses the same permission model as in chrome browser.

Resources

  1. Chrome Custom Tabs:  https://developer.chrome.com/multidevice/android/customtabs
  2. Chrome Custom Tabs Github Repo: GitHub – GoogleChrome/custom-tabs-client: Chrome custom tabs
  3. Android Blog: Android Developers Blog: Chrome custom tabs smooth the transition
  4. Video: Chrome Custom Tabs: Displaying 3rd party content in your Android

 

Continue ReadingChrome Custom Tabs Integration – SUSI.AI Android App

Building PSLab Android app with Fdroid

Fdroid is a place for open source enthusiasts and developers to host their Free and Open Source Software (FOSS) for free and get more people onboard into their community. Hosting an app in Fdroid is not a fairly easy process just like hosting one in Google Play. We need to perform a set of build checks prior to making a merge request (which is similar to pull request in GitHub) in the fdroid-data GitLab repository. PSLab Android app by FOSSASIA has undergone through all these checks and tests and now ready to be published.

Setting up the fdroid-server and fdroid-data repositories is one thing. Building our app using the tools provided by fdroid is another thing. It will involve quite a few steps to get started. Fdroid requires all the apps need to be built using:

$ fdroid build -v -l org.fossasia.pslab

 

This will output a set of logs which tell us what went wrong in the builds. The usual one in a first time app is obviously the build is not taking place at all. The reason is our metadata file needs to be changed to initiate a build.

Build:<versioncode>,<versionname>
    commit=<commit which has the build mentioned in versioncode>
    subdir=app
    gradle=yes

 

When a metadata file is initially created, this build is disabled by default and commit is set to “?”. We need to fill in those blanks. Once completed, it will look like the snippet above. There can be many blocks of “Build” can be added to the end of metadata file as we are advancing and upgrading through the app. As an example, the latest PSLab Android app has the following metadata “Build” block:

Build:1.1.5,7
    commit=0a50834ccf9264615d275a26feaf555db42eb4eb
    subdir=app
    gradle=yes

 

In case of an update, add another “Build” block and mention the version you want to appear on the Fdroid repository as follows:

Auto Update Mode:Version v%v
Update Check Mode:Tags
Current Version:1.1.5
Current Version Code:7

 

Once it is all filled, run the build command once again. If you have properly set the environment in your local PC, build will end successfully assuming there were no Java or any other language syntax errors.

It is worth to mention few other facts which are common to Android software projects. Usually the source code is packed in a folder named “app” inside the repository and this is the common scenario if Android Studio builds up the project from scratch. If this “app” folder is one level below the root, that is “android/app”, the build instructions shown above will throw an error as it cannot find the project files.

The reason behind this is we have mentioned “subdir=app” in the metadata file. Change this to “subdir=android/app” and run the build again. The idea is to direct the build to find where the project files are.

Apart from that, the commit can be represented by a tag instead of a long commit hash. As an example, if we had merge commits in PSLab labeled as “v.<versioncode>”, we can simply use “commit=v.1.1.5” instead of the hash code. It is just a matter of readability.

Happy Coding!

Reference:

  1. Metadata : https://f-droid.org/docs/Build_Metadata_Reference/#Build
  2. PSLab Android app Fdroid : https://gitlab.com/fdroid/fdroiddata/merge_requests/3271/diffs
Continue ReadingBuilding PSLab Android app with Fdroid

Creating Device Screen to show connection status of PSLab Device

For using the PSLab Device the user needs to connect the PSLab device to an Android Phone having a PSLab android app. So there should be a screen that should be able to show the proper status of the PSLab device connection to the android app dynamically and it should also contain instructions on “How to connect the device to the app”.

So, in this blog we will create a device screen which shows the proper status of the connection of the PSLab device with the phone.

First step will be designing the layout for the device screen, for this we will create a fragment named HomeFragment and for its layout we will make use of the Relative Layout as view group and then create a Linearlayout inside it and position it at the center so that it always appears at the center in different screen sizes.

Then inside the LinearLayout, we will create(as shown in respective order) :

  1. ImageView and TextView for showing the status of device connection.
  2. Linear Layout with multiple TextView showing instructions on “How to connect the device to the screen”.
  3. A TextView that will direct the user to a webview showing PSLab website.

After creating all the above views we have created the layout will look like this: –

Now for showing the PSLab connection status dynamically, we have to implement following logic:

  1. When the device is connected it should show the connected icon and text and hide the instructions.
  2. When the device is disconnected it should show the disconnected icon and text and also the instructions.

For this, we will create a method inside the HomeFragment Java file which make use of Arguments deviceConnected and deviceFound to store device connected status.

public static HomeFragment newInstance(boolean deviceConnected, boolean deviceFound) {
HomeFragment homeFragment = new HomeFragment();
homeFragment.deviceConnected = deviceConnected;
homeFragment.deviceFound = deviceFound;
return homeFragment;
}

When both arguments are true we will show the connected text and icon and hide the instructions.

And when both arguments are false we will show the disconnected text and icon and display the instructions.

if (deviceFound && deviceConnected) {
   tvConnectMsg.setVisibility(View.GONE);
   tvVersion.setText(scienceLab.getVersion());
   tvVersion.setVisibility(View.VISIBLE);
   imgViewDeviceStatus.setImageResource(R.drawable.icons8_usb_connected_100);
   tvDeviceStatus.setText(getString(R.string.device_connected_successfully));
} else {
 imgViewDeviceStatus.setImageResource(R.drawable.icons_usb_disconnected_100);
 tvDeviceStatus.setText(getString(R.string.device_not_found));
}

How do we know that the device is connected?

For this, we have to handle the USB Attach event [1] that is whenever the USB is connected the Android will give a broadcast of USB connected and on receiving that broadcast in the app we will replace the HomeFragment giving setting both arguments to true. 

We will create a Broadcast Receiver[2] in the main activity which executes it’s onReceive() method on receiving USB attach event.

private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
   public void onReceive(Context context, Intent intent) {
     String action = intent.getAction();
     if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
       UsbDevice device =  intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
       if(device!=null){                                                  
         getSupportFragmentManager().beginTransaction().replace(R.id.frame,                                            
           HomeFragment.newInstance(true, true)).commitAllowingStateLoss();
         }           
      }
   }
};

Here In the OnReceive Method, we will replace our device screen fragment by passing parameters deviceConnected = true and deviceFound = true to HomeFragment newInstance() method.

Every time we create a Receiver we have to bind corresponding intent filters with broadcast receivers when the application is created.

IntentFilter filter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED);
registerReceiver(mUsbReceiver, filter);

Similarly, we also have to handle the USB Detach event [2], here we will create a Broadcast Receiver[2] which executes in onReceive() method whenever the device is detached and here inside onReceive() method we will replace our device screen by passing parameters deviceConnected = false and deviceFound = false to newInstance() method in HomeFragment.

private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
   public void onReceive(Context context, Intent intent) {
     String action = intent.getAction();
     if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {                                           
getSupportFragmentManager().beginTransaction().replace(R.id.frame,                                            
           HomeFragment.newInstance(false, false)).commitAllowingStateLoss();
         }           
      }
   }
};

Thus, as shown in fig. 2 we have shown the PSLab device connection status dynamically on the screen by handling the USB attach/detach events.

Figure 2 shows the UI of ‘Device Screen’ for the two possible status: ‘not connected’ and ‘connected’

Resources

  1. Codepool Blog – “How to monitor USB events on Android?” by Xiao Ling
  2. Vogella article “What is Broadcast Receiver and how to insert it your app?”
Continue ReadingCreating Device Screen to show connection status of PSLab Device