Android Drawables for Multiple Screens

Android runs on an assortment of devices that offer different screen sizes and densities. For applications, Android system provides a consistent development environment across devices and handles most of the work to adjust each application’s user interface to the screen on which it is displayed.

Range of supported Screens:

Android provides support for multiple screen sizes and densities, reflecting the many different screen configurations that a device may have. One can use features of the Android system to optimise the application’s user interface for each screen configuration and ensure that the application not only renders properly, but provides the best user experience possible on each screen.

A set of six generalised densities:

  • ldpi (low) ~120dpi
  • mdpi (medium) ~160dpi
  • hdpi (high) ~240dpi
  • xhdpi (extra-high) ~320dpi
  • xxhdpi (extra-extra-high) ~480dpi
  • xxxhdpi (extra-extra-extra-high) ~640dpi

 

  Low Density(120), ldpi Medium Density(160), mdpi High Density(240), hdpi Extra-High Density(320), xhdpi
Small Screen QVGA (240×320)   480×640  
Normal Screen WQVGA400 (240×400)

WQVGA432 (240×432)

HVGA (320×480) WVGA800 (480×800)

WVGA854 (480×854)

600×1024

640×960
Large Screen WVGA800 (480×800)

WVGA854 (480×854)

WVGA800 (480×800)

WVGA854 (480×854)

600×1024

   
Extra-Large Screen 1024×600 WXGA (1280×800)

1024×768

1280×768

1536×1152

1920×1152

1920×1200

2048×1536

2560×1536

2560×1600

 

Formula for pixel

px=dp*(dpi/160)
dp→ Density Independent Pixel

dpi→ Dots per Inch

px→ Pixels

ppi→ Pixel per Inch

Step 1: Create a New Project with Android Studio.

Name the application to {anything of your choice} & then click Next. I have currently named it multiresasset.

Step 2:  Configure your App

Select the API Version (I took it as 15) as per your Target Audience. Under Phone and Tablet select the API and the click Next.

        Select Empty Activity and then click Next.

Keep the Activity name as MainActivity (or any name of your choice) and click Finish.

MainActivity is the Default name

 

ONCE THE PROJECT IS LOADED :

Step 3: Code Setup

In the Android Explorer Dropdown select res–>layout and then activity_main.xml

Under activity_main.xml change the layout to Relative Layout and then write the following code:

<ImageView
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:id="@+id/imageview"
 android:src="@drawable/scene"
 android:layout_centerVertical="true"
 android:layout_centerHorizontal="true"/>
If you want to run the same image in Landscape mode, right click on layout under the res folder. Select New and then click on Layout resource file.

After making a new Layout Resource file, keep the following values for the New Resource File.

After clicking on Orientation click on the >> arrows so that you can choose the Screen Orientation type.

It will look something like the above image.

Step 4: Add Repository

In the Menu Bar click on File, and then click on Settings

Once the Settings tab is open, click on Plugins and then click on Browse Repositories.

Search for the repository called Android Drawable Importer and install the same. After installation Restart Android Studio.

Under the Android Explorer Dropdown.

          1) Right click on Res Folder–> New–> Multusource-Drawable

          2) Select the Image(for the formats you need i.e LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI and TVDPI) keep the Resource name as the name you want in the Drawables folder and click OK.

Double click on the java folder–> Package Name and then on MainActivity.

Under MainActivity write the following after setContentView(R.layout.activity_main);

ImageView myimage = (ImageView)findViewById(R.id.imageview);
 myimage.setImageResource(R.drawable.scene);
 PhotoViewAttacher photoView = new PhotoViewAttacher(myimage); //for the Zoom Feature
 photoView.update();

Step 5:  Project Settings

Under the Gradle Scripts, click on build.gradle(Project:multiresasset) import the following maven:

maven {url "https://jitpack.io"}

The above line should be written after the following:

allprojects {
 repositories {
 google()
 jcenter()
 //paste the maven line here
 }

Click on build.gradle(Module:app) and add the following library under the dependencies

//Add Library
 compile 'com.github.chrisbanes:PhotoView:1.2.6'

Step 6:  Sync Gradle

To test the code you can take the same image and test it on different devices.

Also, to check you can delete the previous LDPI, MDPI, HDPI, XHDPI formats. Then load a picture which is less clear and compare it with the XXHDPI and XXXHDPI image.(This step has particularly been done to show the difference that the image is picked by the application with respect to the Screen Resolution)

The picture will adjust according to the Resolution of the Screen(ppi density).

I have tested the code on the following devices:

  • Xiaomi Redmi Note 4 (∽401 ppi)
  • Xiaomi Mi A1 (∽403 ppi)
  • Asus Zenpad 8 (∽189 ppi)
  • Samsung J1 (∽245 ppi)

OUTPUT:

(Landscape Mode)

(PORTRAIT MODE)

 

(Distorted image on Tablet in accordance to the Screen resolution)

How to make Build Variants in Android Studio?

We may need to create different versions of an APK file based on an application type (free or paid application), the server environment type (QA, UAT)  & etc.

To reduce the convolution of making different versions of an APK file, Android Studio uses Gradle, a build toolkit, to automate and manage the build process. It allows us to define flexible custom build configurations. Each build configuration can define its own set of code and resources while reusing parts common to all the application versions. It enables us to have multiple similar versions of an app within a single code base like different colors, dependencies & etc.

Step 1: Create a New Project with Android Studio.

Name the Application to {anything of your choice} & then click Next. I have currently named it buildvariant.

Step 2:  Configure your app

Select the API Version (I took it as 15) as per your Target Audience. Under Phone and Tablet select the API and the click Next.

Select Empty Activity and then click Next.

Keep the Activity name as MainActivity (or any name of your choice) and click Finish.

MainActivity is the Default name

Step 3:  Project Settings

Under the heading Gradle Scripts browse for build.gradle(Module:app)

Append the build.gradle file with the following under the buildTypes DSL:

buildTypes{
         ...
         <your existing code/configurations>
         ...
}
        qa {
            initWith debug
            jniDebuggable true
            applicationIdSuffix ".qa" //uniquely identify the app qa
            manifestPlaceholders = [buildtestAppName: "buildtest qa"] //used to change the name of the app according to the build variant
        }

        uat {
           initWith debug
           jniDebuggable true
           applicationIdSuffix ".uat" //uniquely identify the app uat
           manifestPlaceholders = [buildtestAppName: "buildtest uat"] //used to change the name of the app according to the build variant
       }
}

You can take build variant names as per your choice. (I have made assumptions of taking the build variants as qa and uat.)

Step 4:  Sync Gradle

After the Sync is complete from the buildvariants tab, select the Variant you have to work on.

Under the Manifests file select the AndroidManifest.xml file and change the android:label to

android:label="${buildtestAppName}"

Step 5: Directory and Code Setup.

Click on Explorer dropdown and select Project.

  1. Click on app–>src
  2. Right click on src–> New–> Directory
  3. Give name to the Directory and then click on the Named Directory
  4. Right click on the Directory–> New–> Folder–> Res Folder
  5. Under Res Folder–> New–> Image Asset
  6. Select the Image and click Next and then click Finish.

OR

After creating the Res Folder, copy the image and Paste the same into the Res Folder.

Step 6: Using build variants

Under QA folder, create a XML layout and name it splash_layout.

Write the following code under splash_layout.xml:

<ImageView
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:src="@drawable/qa"
 android:scaleType="centerCrop"/>

Note: Similarly recreate Step 6 for UAT with the same name as the one kept in QA.

Step 7: In the main folder add a New Empty Activity and name it SplashActivity.

SplashActivity consists of the following code:

package com.example.jrb.buildtest;
 import android.content.Intent;
 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
 public class SplashActivity extends AppCompatActivity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.splash_layout);

Step 8. In the AndroidManifest.xml check for the activity and make sure on keeping it attached to the SplashActivity.

Step 9. Hallelujah we are done, now Debug your Application according to the build variant.

 

OUTPUT

Remotely switch On/Off an LED using PubNub and Raspberry PI

Have you ever wanted to control your electrical devices with just the touch of a screen. This can be done via Internet of Things.

The Internet of things (IoT) is the inter-networking of physical devices, vehicles (also referred to as “connected devices” and “smart devices”), buildings, and other items embedded with electronics, software, sensors, actuators, and network connectivity which enable these objects to collect and exchange data.

In this tutorial you will learn how to control a led bulb using your phone or computer from anywhere. The Internet of things (IoT) is the inter-networking of physical devices, vehicles (also referred to as “connected devices” and “smart devices”), buildings, and other items embedded with electronics, software, sensors, actuators, and network connectivity which enable these objects to collect and exchange data.For setup you will need :

  • Raspberry PI 3 or 2
  • Led
  • Male/Female jumper wires
  • Register (220Ω)
Raspberry PI-3
Raspberry PI-3

 

Step 1:

Setup Raspberry PI circuit for LED. Please refer the image below to complete the circuit.
Circuit
Circuit

Step 2:

We are using the RASPBIAN operating system. You can easily download from here :
We are using the python gpiozero liberary to control the LED. For this you have to install python gpiozero library.
Open terminal and execute following commands:

sudo apt-get update
sudo apt-get install python3-gpiozero (recommended) //Python 3

                OR

sudo apt-get install python-gpiozero                //Python 2

Step 3:

Create a python script file in your RASPBIAN operating system to control the LED. Here we name this file to smart-led.py.

from gpiozero import LED
led = LED(17) (Here 17 is the GPIO pin)

led.on() //On the LED
led.off()// Off the LED

Now open the termincal and execute the python file using

python smart-led.py

Hurray !! Now you can control the LED.

Step 4:

Now we are introducing the Pubnub so that you can control your devices from anywhere. For this you have to install pubnub Libraries and Drivers.
Open terrminal and execute following commands:
Install pip    :

sudo apt-get install python-pip

Install pubnub :

sudo pip install pubnub

Step 5: 

Create a free account in Pubnub so that you can get the subscribe_key and the publish_key.
You can create your Pubnub account from here
Pubnub-Dashboard
Pubnub-Dashboard

Step 6:

Now we are going to integrate Pubnub libraries in your python script


from pubnub.callbacks import SubscribeCallback
from pubnub.enums import PNStatusCategory
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub

pnconfig = PNConfiguration()

pnconfig.subscribe_key = <Your PUBNUB subscribe key>
pnconfig.publish_key = <Your PUBNUB publish key>

pubnub = PubNub(pnconfig)

You have to write the pubnub subscriber

def my_publish_callback(envelope, status):
    # Check whether request successfully completed or not
    if not status.is_error():
        pass  # Message successfully published to specified channel.
    else:
        pass  # Handle message publish error. Check 'category' property to find out possible issue
        # because of which request did fail.
        # Request can be resent using: [status retry];

class MySubscribeCallback(SubscribeCallback):
    def presence(self, pubnub, presence):
        pass  # handle incoming presence data

    def status(self, pubnub, status):
        if status.category == PNStatusCategory.PNUnexpectedDisconnectCategory:
            pass  # This event happens when radio / connectivity is lost

        elif status.category == PNStatusCategory.PNConnectedCategory:
            # Connect event. You can do stuff like publish, and know you'll get it.
            # Or just use the connected event to confirm you are subscribed for
            # UI / internal notifications, etc
            pubnub.publish().channel("awesomeChannel").message("hello!!").async(my_publish_callback)
        elif status.category == PNStatusCategory.PNReconnectedCategory:
            pass
            # Happens as part of our regular operation. This event happens when
            # radio / connectivity is lost, then regained.
        elif status.category == PNStatusCategory.PNDecryptionErrorCategory:
            pass
            # Handle message decryption error. Probably client configured to
            # encrypt messages and on live data feed it received plain text.

    def message(self, pubnub, message):
#        print(message.message)
        if 'status' in message.message:
            print(message.message['status'])
            whatToDo(message.message['status'])
        pass  # Handle new message stored in message.message

def whatToDo(status):
    if status == 'ON':
        print('Switch ON light')
        # switch on
        led.on()
    else:
        print('Swtich OFF light')
        # switch off
        led.off()

pubnub.add_listener(MySubscribeCallback())
pubnub.subscribe().channels(<Your pubnub channel name>).execute()

Step 7:

We are using pubnub javascript library for publishing the message through web page. Create a simple html file for e.g. Button.html
Setup Pubnub:
<script src=”https://cdn.pubnub.com/pubnub.min.js“></script>

var pubnub = PUBNUB.init({
        publish_key: <Your PUBNUB subscribe key>,
        subscribe_key: <Your PUBNUB publish key>
    });

Create Buttons:

<button type="button" onClick="lightOn()" class="on">ON</button>
<button type="button" onClick="lightOff()" class="off">OFF</button>

Publish messages:
Here we are sending ON/OFF status that can handel by your python script.

function lightOff(){
    pubnub.publish(
     {
        message: {
            status: 'OFF'
        },
        channel: 'awesomeChannel',
        sendByPost: false, // true to send via post
        storeInHistory: false, //override default storage options
        meta: {
            "cool": "meta"
        }   // publish extra meta with the request
    },
    function (status, response) {
        if (status.error) {
            // handle error
            console.log(status)
        } else {
            console.log("message Published w/ timetoken")
        }
    }
  );

}

function lightOn(){
    pubnub.publish(
     {
        message: {
            status: 'ON'
        },
        channel: 'awesomeChannel',
        sendByPost: false, // true to send via post
        storeInHistory: false, //override default storage options
        meta: {
            "cool": "meta"
        }   // publish extra meta with the request
    },
    function (status, response) {
        if (status.error) {
            // handle error
            console.log(status)
        } else {
            console.log("message Published w/ timetoken")
        }
    }
  );
}

Open this file to chrome or any other web browser.
You can host this html file to some cloud server like (AWS, heroku) to access from anywhere.

Step 8:

!!! Enjoy !!!
Hope this tutorial helps you to use Pubnub to control your electrical devices via network.

What is Cross-site Scripting (XSS) and it’s types

If you are into the hacking techniques, you sure must have heard of this popular terminology XSS (Cross-Site Scripting). This is one of the techniques rather a vulnerability in which an attacker/hacker can input something (harmful mostly) which is sent to unsuspecting victims.

What follows below will get you up to speed on the fundamental concept in just a few paragraphs.

What is XSS

Cross-site Scripting (XSS) refers to client-side code injection attack wherein an attacker can execute malicious scripts (also commonly referred to as a malicious payload) into a legitimate website or web application.

XSS is amongst the most rampant of web application vulnerabilities and occurs when a web application makes use of unvalidated or unencoded user input within the output it generates.

In XSS, an attacker does not target a victim directly. Instead, an attacker would exploit a vulnerability within a website or web application that the victim would visit, essentially using the vulnerable website as a vehicle to deliver a malicious script to the victim’s browser.

How XSS works

In order to run malicious JavaScript code in a victim’s browser, an attacker must first find a way to inject a payload into a web page that the victim visits. Of course, an attacker could use social engineering techniques to convince a user to visit a vulnerable page with an injected JavaScript payload.

In order for an XSS attack to take place the vulnerable website needs to directly include user input in its pages. An attacker can then insert a string that will be used within the web page and treated as code by the victim’s browser.

The consequences of malicious JavaScript

  • Cookie theft: The attacker can access the victim’s cookies associated with the website
  • Keylogging: The attacker can register a keyboard event listener using javascript and then send all of the user’s keystrokes to his own server, potentially recording sensitive information such as passwords and credit card numbers.
  • Phishing: The attacker can insert a fake login form into the page using DOM manipulation, set the form’s action attribute to target his own server, and then trick the user into submitting sensitive information.

Types of XSS

While the goal of an XSS attack is always to execute malicious JavaScript in the victim’s browser, there are few fundamentally different ways of achieving that goal. XSS attacks are often divided into three types:

  • Persistent XSS: where the malicious string originates from the website’s database.
  • Reflected XSS: where the malicious string originates from the victim’s request.
  • DOM-based XSS: where the vulnerability is in the client-side code rather than the server-side code.