Generating Badges for Manual Data for Pre-Selected Badges

BadgeYay is a Badge Generator developed by FOSSASIA. In recent time there was a BUG that caused the badge generator to throw errors and malfunction while generating the badges.

This error was first reported by me, @gabru-md. And later when everyone seemed to have this bug it was resolved after a complete 48 hour of reverse engineering the code.

What was the Bug?

The bug with the generator was that the server side API did not function well and was not generating badges in cases of Manual Input and Pre-Selected Images.The issue was first made sure and then created on github as Issue number 314 .

Resolving the Bug

Resolving the bug this time was a hard task as the code was not properly maintained due to many PRs being merged and due to this it took me 48 hours to figure out what was wrong with the code.

After like 1 day of reading between the lines it was found out that the bug was caused due to improper “if…else” conditions. There were several  small bugs that arouse when this main bug was being dealt with.

How was it resolved?

Many changes were done to the code to resolve the bug. It was definitely the most time consuming and important fix that I had ever applied to any project.

The only changes were done to the main server file “main.py”.

  • Adding a missing line to the file.
text_on_image = request.form[“text_on_image”]

 

  • Removing unnecessary code for cleaning up the file.
if file.filename == ‘’  and csv ==  ‘’:

    flash(‘Please select a CSV field to upload’)

    return redirect(url_for(‘index’))

 

And

elif:

    if file.find(“png.csv”) != -1:

        if img == ‘’:

            flash(‘{Please upload an image in ...’)   

            return redirect(url_for(‘index’))

    else:

        flash(‘Please upload ...’)

 

  • Adding the relevant code to fix the bug.

 

if img == ‘’:

    img = request.filed[‘image’].filename

    filename = request.files[‘image’].filename + “.csv”

elif csv != ‘’:

Changing filename to “img + .csv” resolved the filename error that caused the badge generator not to recognize the files.

Saving the files to the correct places for the script to recognize them

image.save(os.path.join(app.config[‘UPLOAD_FOLDER’],image.filename))

 

Changing the rest of the code to comply with the changes and make Badgeyay BUG free.

elif eventyay_url != ‘’:

    filename = ‘speaker.png.csv’

    generate_csv_eventyay.tocsv(eventyay_url,filename)

if filename.find(‘png.csv’) != -1:

    if img == ‘’:

        flash(“Please Upload …”)

        return redirect(url_for(‘index’))

else:

    flash(‘Please Upload a CSV …’)

    return redirect(url_for(‘index’))

 

The last change was to change an “if” condition to a relevant one.

if csv == ‘’ and filename == img + ‘.csv’ and eventyay_url == ‘’:

 

All these changes helped resolve one of the major bugs in Badgeyay. With the merging of the associated PR the bug was immediately fixed and Badgeyay was up again.

Challenges

  • Lack of time since service was down for a long time
  • Improper code

 

But I took them as challenges and was able to fix it for once and for all.

Further Improvements

Further Improvements will be leading to a more fast and stable Badgeyay with more user friendly options and an improved UI and stronger UX.

Resources

 

Continue ReadingGenerating Badges for Manual Data for Pre-Selected Badges

Toggling Voice On/Off in SUSI Chromebot

SUSI Chromebot has a lot of features that make it one of the best projects of FOSSASIA.

Recently Voice/Speech was added to SUSI Chromebot. But there was no option that controlled the fact that whether speech output is needed or not.

The latest addition to SUSI Chromebot is Toggling the Voice of SUSI On or Off.

How was it achieved?

Toggling Voice for SUSI required adding a button and a snippet of Javascript code to the main JS file. The code will take care of the fact whether the voice is to be toggled on or off.

I started off by adding a button to the main HTML file.

<a href=”javascript: void(0)” id=”speak” style=”color: white”><i class=”material-icons” id=”speak-icon”>volume_up</i></a>

The above snippet of HTML code adds a voice button to the top bar of chromebot.

Then there was the major part where the javascript code was to be added to add the functionality to the button.

var shouldSpeak = true;

I started off by creating a variable called as “shouldSpeak” which will determine whether or not SUSI should use the Chrome’s API to speak.

Then I changed the “speakOut()” function and added another parameter to it.

function speakOut(msg,speak=false){

if(speak){

var voiceMsg = new SpeechSynthesisUtterance(msg);

window.speechSynthesis.speak(voiceMsg);

}

}

The above code made sure that susi was only allowed to speak when and only “speak” variable was set to true.

Then “eventListeners” were added to buttons and other things to link the functionality.

document.getElementById(‘speak’).addEventListener(‘click’,changeSpeak);

It adds the events of click to “speak” and associates it with the function “changeSpeak”.

Now the function “changeSpeak” is created as follows. It toggles the on/off mechanism of voice in SUSI Chromebot.

function changeSpeak(){

shouldSpeak = !shouldSpeak;

var SpeakIcon = document.getElementById(‘speak-icon’);

if(!shouldSpeak){

SpeakIcon.innerText = “volume_off”;

}

else{

SpeakIcon.innerText = “volume_up”;

}

console.log(‘Should be speaking? ’ + shouldSpeak);

}

Everytime the user clicks on the icon to toggle on/off voice the icon must also change and this functionality was taken care of by the above piece of code.

Resources

 

Continue ReadingToggling Voice On/Off in SUSI Chromebot

Resolving Internal Error on Badgeyay

Badgeyay is in development stage and is frequently seen to encounter bugs. One such bug is the Internal Server Error in Badgeyay.

What was the bug?

The bug was with the badge generator’s backend code. The generator was trying to server the zip file that was not present. After going through the log I noticed that it was because a folder was missing from Badgeyay’s directory.

 

I immediately filed an issue #58 which stated the bug and how could it be resolved. After being assigned to the issue I did my work and created a Pull Request that was merged soon.

The Pull Request can be found here.

Resolving the bug

With the help of extensive error management and proper code and log analysis I was able to figure out a fix for this bug. It was in-fact due to a missing folder that was deleted by a subsequent code during zipfile/pdf generation. It was supposed to be recreated every time it was deleted. I quickly designed a function that solved this error for future usage of Badgeyay.

 

How was it resolved?

First I started by checking if the “BADGES_FOLDER” was not present. And if it was not present then the folder was created using the commands below

 

if not os.path.exists(BADGES_FOLDER):

    os.mkdir(BADGES_FOLDER)

 

Then, I added docstring to the remaining part of the code. It was used to empty all the files and folder inside the “BADGES_FOLDER”. We could have to delete two things, a folder or a file.

So proper instructions are added to handle file deletion and folder deletion.

 

for file in os.listdir(BADGES_FOLDER):

    file_path = os.path.join(BADGES_FOLDER, file)

    try:

        if os.path.isfile(file_path):

            os.unlink(file_path)

        elif os.path.isdir(file_path):

            shutil.rmtree(file_path)

    except Exception:

        traceback.print_exc()

 

Here “os.unlink” is a function that is used to delete a file. And “shutil.rmtree” is a function that deletes the whole folder at once. It is similar to “sudo rm -rf /directory”. Proper error handling is done as well to ensure stability of program as well.

Challenges

There were many problems that I had to face during this bug.

  • It was my first time solving a bug, so I was nervous.
  • I had no knowledge about “shutil” library.
  • I was a new-comer.

But I took these problems as challenges and was able to fix this bug that caused the INTERNAL SERVER ERROR : 500 .

Resources

 

 

Continue ReadingResolving Internal Error on Badgeyay

Contributing to Open Event Android App

The Open Event Android project consists of two components. The App Generator is a web application that is hosted on a server and generates an event Android app from a zip with JSON and binary files (examples here) or through an API. The second component we are developing in the project is a generic Android app – the output of the app generator. The Android app has a standard configuration file, that sets the details of the app (e.g. color scheme, logo of event, link to JSON app data).

The process for making a contribution in the project starts with making your account on GitHub. Secondly find the open source projects that interest you. Now as for me I started with open-event-android. Then follow these steps:

  1. Go through the project’s README.md file and get information about the various aspects and technologies of the project.
  2. Now fork that repo in your account.
  3. Open or setup the project as per the given information present in its documentation, for example for the sample android app you have to clone the project in your local machine and open it up using Android Studios.

Now you have your version of the project now it’s time for you to use the project on your own.

While doing so you have to work like a tester of the project, so you should explore each and every bit and find out any possible anomaly in the project that you would like to work on. Once you have that you are ready to create an issue.

Following are the steps to create a new issue,

Navigate to the main repo link, you will see an issues section as follows:

  • Click the new issue button and report every detail about the issue. For eg. The first issue that i worked on was Issue-1934
  • Even if you don’t find any problem in the project on your own you can always work on issues created by others, you just have to let the maintainers know that you want to work on the issue by commenting in it Issue 1709.
  • Now the next step is to work on that issue
  • On your machine you don’t have to change the code in the development branch as it’s considered to be as a bad practice. Hence checkout as a new branch. For eg. I checked out for the above issue as ‘crashfixed’
  • Make the necessary changes to that branch and test that the code is compiling and the issue is fixed followed by
  • The add command is used to bring the changes to the staging area so that they are ready to be committed/saved. You can also add individual files with the command
  • Next we want to save the changes that we made till now which can be done through git commit.
  • Finally we would push the changes that we made to our forked repository in github.
  • Now navigate to the repo and you will an option to create a Pull Request.
    Mention the Issue number and description and changes you done ,include screenshots of the fixed app.For eg.My first PR was  Pull Request 1936.

Sending the pull request is asking the maintainers of the code to add your changes to the main project which would be visible to all the contributors. But before getting merged your code may have to pass through several tests as in my case were:

-codacy/pr

-continuous-integration/travis-ci/pr

After your code passes the above tests you you would require one approved review from one of the maintainers of the project to get your code merged into the main one.

If your code is perfect in the very first attempt it would be accepted by the maintainer otherwise you would be asked to do some changes in it. You could carry out the changes on your local machine and once you are done with them you could push them to your forked repository and the changes would be amended in your pull request on its own.

Resources

Continue ReadingContributing to Open Event Android App

Option to Print Photos in the Phimpme Android Application

In the Phimpme Android application, users can perform various operations on the photos available such as copy, move, add the image to favourites collection, share the images with others, use it as covers, wallpapers and much more. However one another important functionality that has been added in the Phimpe Android application is printing of images. In this post we will be discussing about the implementation of the above mentioned functionality.

Step 1

First we need to create an instance of the class PrintHelper passing context as the constructor parameter which can be done with the following line of code.

PrintHelper photoPrinter = new PrintHelper(this);

Step 2

Now a  function call of setScalemode() is done where we require passing a parameter out of the two options SCALE_MODE_FIT and SCALE_MODE_FILL. The difference between the two options is explained below.

SCALE_MODE_FIT – This option sizes the image so that the whole image is displayed within the printable area of the page.

SCALE_MODE_FILLThis option scales the image so that it fills the entire printable area of the page. Choosing this setting means that some portion of the top and bottom, or left and right edges of the image is left out. This option is the default value if no scale mode is set.

Though neither of the scaling options alter the existing aspect ratio of the image, we are going with the latter of the two as the requirement here is to display the whole image in the printable area. The following code snippet is used to perform the desired function call.

photoPrinter.setScaleMode(PrintHelper.SCALE_MODE_FIT);

Step 3

After obtaining an instance of the class PrintHelper and calling the function setScalemode with the proper scale parameter, the path of the image to be printed is extracted and is passed in as a parameter to the decodefile function of the class BitmapFactory which has another parameter.

A Bitmap object is the return result of the operation performed by the function decodefile. The Bitmap object is thereafter passed in as a parameter to the printBitmap() function of the PrintHelper class along with a string attribute which will denote the file name of the printed photo. The code snippet to the above mentioned operations are given below.

Bitmap bitmap = BitmapFactory.decodeFile(getAlbum().getCurrentMedia().getPath(), new BitmapFactory.Options());
photoPrinter.printBitmap(getString(R.string.print), bitmap);

After the printbitmap() is called no further action is required from the side of the application. The Android system print interface appears where the users can select the printing options. The user can proceed to print the image or cancel the operation. If the user decides to proceed with the operation a print job is created and printing operation notification appears in the system navigation bar. The system print interface appearing is displayed below.

This is how we have achieved the functionality of printing images in the Phimpme Android application. To get the full source code, please refer to the Phimpme Android GitHub repository listed in the resources section below.

Resources

1.Android Developer Guide – https://developer.android.com/training/printing/index.html

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

3.PrintHelper Class Guide – https://developer.android.com/reference/android/support/v4/print/PrintHelper.html

 

Continue ReadingOption to Print Photos in the Phimpme Android Application

Participate in the #OpenTechNights Program today and Win a Free Stay during the FOSSASIA Summit 2018 from the Open Source Initiative and UNESCO

The FOSSASIA Summit 2018 takes place in Singapore from Thursday, March 22 – Sunday, March 25. Open Source contributors can now apply for a free ticket to the event, and accommodation throughout the conference. In addition, you’ll be eligible to participate in: Featured cloud workshops, the UNESCO hackathon, and celebrate the 20th Anniversary of the Open Source Initiative. All you have to do is convince us, that you are an awesome Open Source contributor and book your trip to Singapore!

About #OpenTechNights

Developers from all over the world are joining the FOSSASIA Summit. We want to connect established and new Open Tech contributors alike. With the support of UNESCO, the Open Source Initiative, and other partners, we are inviting Free and Open Source Software contributors to join us. Winners will receive free lodging at a shared accommodation in the centre of Singapore, and a free ticket to the conference.

Winners are expected to join the summit each day, to participate in the workshops, and the Hackathon on Saturday/Sunday, March 24/25. We would also hope you can support the Open Source Initiative at their booth.

How do I sign up?

Step 1: Please fill in our form here before February 28, 2018.

Step 2: We will notify all winners within three days of their submission, however judging will begin immediately, and continue until all open spots are filled, so the earlier you apply, the higher your chances to win. Please note, winners will receive free accommodations in Singapore. Flight and other travel costs are not included and are the responsibility of the attendee.

Step 3: Selected applicants must confirm their itinerary and tickets before March 1st to insure their free stay in Singapore. Earliest check-in possible is Wednesday March 21, latest check-out is Monday, March 26. Please indicate your arrival and departure times in the application form.

Expectations of Participants – Share what you learn

  1. Attendees support volunteers, speakers and participants at the event, and take a shift at the Open Source Initiative’s booth. Let’s bring the spirit of sharing Open Technologies and learning together!
  2. Please confirm your participation at the opening event at 12PM, Thursday, March 22, 2018 and participate in the specially featured cloud workshops on Friday, March 23, 2018 from 9.00 AM – 5.00PM.
  3. Attendees participate in the UNESCO Hackathon on Saturday, March 24 (2.00 PM – 10.00PM) and on Sunday, March 25 (9.00 AM – 5.00PM).
  4. Attendees help reach out to community members who cannot join us at the event, make tweets, share what you learn on social media, publish photos and put up blog post about the summit.

Apply Now

Apply for a free stay with #FOSSASIA #OpenTechNights supported by the Open Source Initiative and the UNESCO and participate in the FOSSASIA Summit 2018 now here!

More Information

More updates, tickets and information on speakers on our website: https://2018.fossasia.org

Links

Open Source Initiative: https://opensource.org

UNESCO: http://unesco.org

Continue ReadingParticipate in the #OpenTechNights Program today and Win a Free Stay during the FOSSASIA Summit 2018 from the Open Source Initiative and UNESCO

Announcing the FOSSASIA Codeheat Winners 2017/18

Today we are very proud to announce our Grand Prize Winners and Finalist Winners of Codeheat 2017/2018.

Codeheat was epic in every regard. Participants not only solved a massive amount of issues in FOSSASIA’s projects, reviewed pull requests, shared scrums, and wrote blog posts, but most importantly they encouraged and helped one another to learn and progress along the way. It was a very, very busy 5 months for everyone – we had 647 developers from 13 countries participating in the contest supported by 43 mentors. Thank you all for this amazing achievement!

With so much excellent work getting done, it was a super hard to choose the Grand Prize and Finalist Winners of the contest. Our winners stand out in particular as they contributed to FOSSASIA projects on a continuously high level following our Free and Open Source Best Practices. They worked in different areas – code, reviews, blog posts and supported other community members.

Each of the Grand Prize Winners is awarded a travel grant to join us at the FOSSASIA Summit in Singapore from March 22-25, 2018 where they receive the official Codeheat award, and meet with mentors and FOSSASIA developers. Other Finalist Winners will receive travel support vouchers to go to a Free and Open Source Software event of their choice. Active participants will also receive a certificate over the upcoming weeks. FOSSASIA mentors will meet many contributors and hand out prizes and Tshirts at our regular meetups and events across Asia.

Congratulations to our Grand Prize Winners, Finalist Winners, and all of the participants who spent the last few of months learning, sharing and contributing to Free and Open Source Projects. Well-done! We are deeply impressed by your work, your progress and advancement. The winners are (in alphabetical order):

Grand Prize Winners

Manish Devgan

Parth Shandilya

Raghav Jajodia

Finalist Winners

Anshuman Verma

Ayush Gupta

Bhavesh Anand

Mohit Sharma

Nikit Bhandari

Ritika Motwani

Vaibhav Singh

About Codeheat

Codeheat is a contest that the FOSSASIA organization is honored to run every year. We saw immense growth this year in participants and the depth of contributions.

Thank you Mentors and Supporters

Our 40+ mentors and many project developers, the heart and soul of Codeheat, are the reason the contest thrives. Mentors volunteer their time to help participants become open source contributors. Mentors spend hundreds of hours during answering questions, reviewing submitted code, and welcoming the new developers to project. Codeheat would not be possible without their patience and tireless efforts. Learn more about this year’s mentors on the Codeheat website.

Certificate of Participation

Participating developers, mentors and the FOSSASIA admin team learnt so much and it was an amazing and enriching experience and we believe the learnings are the main take-away of the program. We hope to see everyone continuing their contributions, sharing what they have learnt with others and to seize the opportunity to develop their code profile with FOSSASIA. We want to work together with the Open Tech community to improve people’s lives and create a better world for all. As a participating developer or mentor, you will receive your certificate over the upcoming weeks. Thank you!

More Links

Continue ReadingAnnouncing the FOSSASIA Codeheat Winners 2017/18

Installing Susper Search Engine and Deploying it to Heroku

Susper is a decentralized Search Engine that uses the peer to peer system yacy and Apache Solr to crawl and index search results.

Search results are displayed using the Solr server which is embedded into YaCy. All search results must be provided by a YaCy search server which includes a Solr server with a specialized JSON result writer. When a search request is made in one of the search templates, a HTTP request is made to YaCy. The response is JSON because that can much better be parsed than XML in JavaScript.

In this blog, we will talk about how to install Susper search engine locally and deploying it to Heroku (A cloud application platform).

How to clone the repository

Sign up / Login to GitHub and head over to the Susper repository. Then follow these steps.

  1. Go ahead and fork the repository
https://github.com/fossasia/susper.com

2.   Get the clone of the forked version on your local machine using

git clone https://github.com/<username>/susper.com.git

3. Add upstream to synchronize repository using

git remote add upstream https://github.com/fossasia/susper.com.git

Getting Started

The Susper search application basically consists of the following :

  1. First, we will need to install angular-cli by using the following command:
npm install -g @angular/cli@latest

2. After installing angular-cli we need to install our required node modules, so we will do that by using the following command:

npm install

3. Deploy locally by running this

ng serve

Go to localhost:4200 where the application will be running locally.

How to Deploy Susper Search Engine to Heroku :

  1. We need to install Heroku on our machine. Type the following in your Linux terminal:
wget -O- https://toolbelt.heroku.com/install-ubuntu.sh | sh

This installs the Heroku Toolbelt on your machine to access Heroku from the command line.

  1. Create a Procfile inside root directory and write
web: ng serve
  1. Next, we need to login to our Heroku server (assuming that you have already created an account).

Type the following in the terminal:

heroku login

Enter your credentials and login.

  1. Once logged in we need to create a space on the Heroku server for our application. This is done with the following command
heroku create
  1. Add nodejs buildpack to the app
heroku buildpacks:add –index 1 heroku/nodejs
  1. Then we deploy the code to Heroku.
git push heroku master
git push heroku yourbranch:master # If you are in a different branch other than master

Resources

Continue ReadingInstalling Susper Search Engine and Deploying it to Heroku

Installing the Loklak Search and Deploying it to Surge

The Loklak search creates a website using the Loklak server as a data source. The goal is to get a search site, that offers timeline search as well as custom media search, account and geolocation search.

In order to run the service, you can use the API of http://api.loklak.org or install your own Loklak server data storage engine. Loklak_server is a server application which collects messages from various social media tweet sources, including Twitter. The server contains a search index and a peer-to-peer index sharing interface. All messages are stored in an elasticsearch index.

The site of this repo is deployed on the GitHub gh-pages branch and automatically deployed here: http://loklak.org

In this blog, we will talk about how to install Loklak_Search locally and deploying it to Surge (Static web publishing for Front-End Developers).

How to clone the repository

Sign up / Login to GitHub and head over to the Loklak_Search repository. Then follow these steps.

  1. Go ahead and fork the repository
https://github.com/fossasia/loklak_search
  1.   Get the clone of the forked version on your local machine using
git clone https://github.com/<username>/loklak_search.git
  1.   Add upstream to synchronize repository using
git remote add upstream https://github.com/fossasia/loklak_search.git

Getting Started

The Loklak search application basically consists of the following :

  1. First, we will need to install angular-cli by using the following command:
npm install -g @angular/cli@latest

2. After installing angular-cli we need to install our required node modules, so we will do that by using the following command:

npm install

3. Deploy locally by running this

ng serve

Go to localhost:4200 where the application will be running locally.

How to Deploy Loklak Search on Surge :

Surge is the technology which publishes or generates the static web-page demo link, which makes it easier for the developer to deploy their web-app. There are a lot of benefits of using surge over generating demo link using GitHub pages.

  1. We need to install surge on our machine. Type the following in your Linux terminal:
npm install –global surge

This installs the Surge on your machine to access Surge from the command line.

  1. In your project directory just run
surge
  1. After this, it will ask you three parameters, namely
Email
Password
Domain

After specifying all these three parameters, the deployment link with the respective domain is generated.

Auto deployment of Pull Requests using Surge :

To implement the feature of auto-deployment of pull request using surge, one can follow up these steps:

  • Create a pr_deploy.sh file
  • The pr_deploy.sh file will be executed only after success of Travis CI i.e. when Travis CI passes by using command bash pr_deploy.sh
#!/usr/bin/env bash
if [ “$TRAVIS_PULL_REQUEST” == “false” ]; then
echo “Not a PR. Skipping surge deployment.”
exit 0
fi
npm i -g surge
export SURGE_LOGIN=test@example.co.in
# Token of a dummy account
export SURGE_TOKEN=d1c28a7a75967cc2b4c852cca0d12206
export DEPLOY_DOMAIN=https://pr-${TRAVIS_PULL_REQUEST}-fossasia-LoklakSearch.surge.sh
surge –project ./dist –domain $DEPLOY_DOMAIN;

Here, Travis CI is first installing surge locally by npm i -g surge  and then we are exporting the environment variables SURGE_LOGIN , SURGE_TOKEN and DEPLOY_DOMAIN.

Now, execute pr_deploy.sh file from .travis.yml by using command bash pr_deploy.sh

Resources

Continue ReadingInstalling the Loklak Search and Deploying it to Surge

Camera Controls Using Volume Buttons In The Phimpme Application

The Phimpme Android application has a camera, Gallery section, edit image section and also the inbuilt sharing option. In spite of having all of the above features, the Phimpme application doesn’t compromise on the quality and functions of each of the sections. For instance, we can control the camera fully with the help of just the volume buttons. For this, we have provided an option in the settings of the application to change and select the behaviour of the volume buttons according to the users choice. In this post, I will be discussing how we have achieved this functionality.

Step 1

First, we have to display an ArrayList of options using the ListPreference in the settings. The user can perform the following functions using the volume keys.

  1. Take Photo
  2. Focus
  3. Zoom in/out
  4. Change Exposure Level
  5. Switch Auto Level on/off

There are also two other option to change device volume and to do nothing in case the user wants the default behaviour.

The above options in the settings can be provided using the following lines of code.

<ListPreference
   android:defaultValue="volume_take_photo"
   android:entries="@array/preference_volume_keys_entries"
   android:entryValues="@array/preference_volume_keys_values"
   android:key="preference_volume_keys"
   android:summary="@string/preference_volume_keys_summary"
   android:title="@string/preference_volume_keys" />

Step 2

Now as the user selects a particular option from the ListPreference, the value in the SharedPreference associated with a particular key value gets updated. After this, we have to perform the particular activity as soon as the volume button is pressed. For this, we have to Override the onKeyDown() function of the KeyEvent.Callback class in Android. This function takes in the Integer keycode and the KeyEvent as the parameters.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
   if (MyDebug.LOG)
       Log.d(TAG, "onKeyDown: " + keyCode);
   boolean handled = mainUI.onKeyDown(keyCode, event);
   if (handled)
       return true;
   return super.onKeyDown(keyCode, event);
}

Step 3

We have defined another onKeyDown() method in the MainUI class to keep the code modularized. In this, we have made use of the Switch cases to perform the different actions. This can be done by using the following line of code snippet.

Switch (volume_keys) {
  case "volume_take_photo":
     main_activity.takePicture();
     return true;

  case "volume_zoom":
     if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
        main_activity.getPreview().zoomTo(main_activity.getPreview().getCameraController().getZoom() + 1);
     }
     else {
        main_activity.getPreview().zoomTo(main_activity.getPreview().getCameraController().getZoom() - 1);
     }
     return true;

In the above code snippet, we have defined the function to perform the zoom operation and to click picture using the volume keys. Similarly, we can add the functions to perform all the above mentioned activities. To get the full source code, please refer to the Phimpme Android GitHub repository mentioned in the resources section below.

Resources

  1. Android Developer Guide – KeyEvent.Callback class – https://developer.android.com/reference/android/view/KeyEvent.Callback.html
  2. GitHub – Phimpme Android Repository – https://github.com/fossasia/phimpme-android/
  3. StackOverflow – Handling key events in Android – https://stackoverflow.com/questions/5631977/keyevent-handling-in-android
  4. Blog post – Handleling Key Events – https://android-developers.googleblog.com/2009/12/back-and-other-hard-keys-three-stories.html

 

Continue ReadingCamera Controls Using Volume Buttons In The Phimpme Application