Showing posts with label tutorial. Show all posts
Showing posts with label tutorial. Show all posts

Sunday, 25 May 2014

Change Volume and Brightness using Seekbar

Seekbar:


The SeekBar is an interactive slider widget that allows the user to select one value from a range of values (from 0-max). As the user moves the slider left or right, the value of the SeekBar will change.
OR
A SeekBar is an extension of ProgressBar that adds a draggable thumb. The user can touch the thumb and drag left or right to set the current progress level or use the arrow keys. Placing focusable widgets to the left or right of a SeekBar is discouraged.

Seekbar is the best control for this kind of functions, where you will let user to select a value from your described range like I am going to use in this tutorial for volume and device screen brightness control.

Seekbar has a nested Interface called OnSeekBarChangeListener, It is a callback that notifies user when the progress level has been changed. This includes changes that were initiated by the user through a touch gesture or arrow key/trackball as well as changes that were initiated programmatically.

OnSeekBarChangeListener has three methods that can be used to get current progress value from seekbar at three states:

onProgressChanged: It notifies that progress level has changed, it is really helpful in this post.

onStartTrackingTouch: It notifies that the user has started touch gesture.

onStopTrackingTouch: It notifies that the user has finished touch gesture.


OutPut:
Change Volume and Brightness using Seekbar outputChange Volume and Brightness using Seekbar outputs
Create new Android Project
Project Name: Sound Brightness Settings
//tested from 2.3.3 to current android sdk 
Build Target: Android 2.3.3   //or greater than that
Application Name: SeekBarDemo
Package Name: com.shaikhhamadali.blogspot.soundbrightnesssettings
Create Layout file: activity_main

1. code of Layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
 
    <TextView
        android:id="@+id/tVBrightness"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="180dp"
        android:text="Brightness: " />

  <TextView
      android:id="@+id/tVVolume"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="130dp"
      android:text="Volume: " />

    <SeekBar
        android:id="@+id/sbVolume"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="150dp" />
    
    <SeekBar
        android:id="@+id/sbBrightness"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="200dp"
        >
    </SeekBar>
 
</RelativeLayout>

2. code of activity:

package com.shaikhhamadali.blogspot.soundbrightnesssettings;

import android.media.AudioManager;
import android.os.Bundle;
import android.provider.Settings.SettingNotFoundException;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.provider.Settings.System;

public class MainActivity extends Activity {
 //TextViews to show details of volume and brightness
 private TextView tVBrightness,tVVolume;
 //SeekBars to set volume and brightness
 private SeekBar sbVolume,sbBrightness;
 //AudioManager object, that will get and set volume
 private AudioManager audioManager;
 //Variable to store brightness value
 private int brightness;
 //Content resolver used as a handle to the system's settings
 private ContentResolver cResolver;
 //Window object, that will store a reference to the current window
 private Window window;
 int maxVolume=1;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  //Suggests an audio stream whose volume should be changed by the hardware volume controls. 
  setVolumeControlStream(AudioManager.STREAM_MUSIC);
  initializeControls();
 }


 private void initializeControls() {
  //get reference of the UI Controls
  sbVolume = (SeekBar) findViewById(R.id.sbVolume);
  sbBrightness = (SeekBar) findViewById(R.id.sbBrightness);
  tVVolume=(TextView)findViewById(R.id.tVVolume);
  tVBrightness = (TextView) findViewById(R.id.tVBrightness);

  try {

   audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
   //set max progress according to volume
   sbVolume.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
   //get current volume
   sbVolume.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
   //Set the seek bar progress to 1
   sbVolume.setKeyProgressIncrement(1);
   //get max volume
   maxVolume=sbVolume.getMax();
   sbVolume.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {}

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {}

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress,
      boolean fromUser) {
     audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
     //Calculate the brightness percentage
     float perc = (progress /(float)maxVolume)*100;
     //Set the brightness percentage 
     tVVolume.setText("Volume: "+(int)perc +" %");
    }
   });

  } catch (Exception e) {

  }


  //Get the content resolver
  cResolver = getContentResolver();

  //Get the current window
  window = getWindow();

  //Set the seekbar range between 0 and 255
  sbBrightness.setMax(255);
  //Set the seek bar progress to 1
  sbBrightness.setKeyProgressIncrement(1);

  try
  {
   //Get the current system brightness
   brightness = System.getInt(cResolver, System.SCREEN_BRIGHTNESS);
  } 
  catch (SettingNotFoundException e) 
  {
   //Throw an error case it couldn't be retrieved
   Log.e("Error", "Cannot access system brightness");
   e.printStackTrace();
  }

  //Set the progress of the seek bar based on the system's brightness
  sbBrightness.setProgress(brightness);

  //Register OnSeekBarChangeListener, so it can actually change values
  sbBrightness.setOnSeekBarChangeListener(new OnSeekBarChangeListener() 
  {
   public void onStopTrackingTouch(SeekBar seekBar) 
   {
    //Set the system brightness using the brightness variable value
    System.putInt(cResolver, System.SCREEN_BRIGHTNESS, brightness);
    //Get the current window attributes
    LayoutParams layoutpars = window.getAttributes();
    //Set the brightness of this window
    layoutpars.screenBrightness = brightness / (float)255;
    //Apply attribute changes to this window
    window.setAttributes(layoutpars);
   }

   public void onStartTrackingTouch(SeekBar seekBar) 
   {
    //Nothing handled here
   }

   public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) 
   {
    //Set the minimal brightness level
    //if seek bar is 20 or any value below
    if(progress<=20)
    {
     //Set the brightness to 20
     brightness=20;
    }
    else //brightness is greater than 20
    {
     //Set brightness variable based on the progress bar 
     brightness = progress;
    }
    //Calculate the brightness percentage
    float perc = (brightness /(float)255)*100;
    //Set the brightness percentage 
    tVBrightness.setText("Brightness: "+(int)perc +" %");
   }
  });        
 }



}

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shaikhhamadali.blogspot.soundbrightnesssettings"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.shaikhhamadali.blogspot.soundbrightnesssettings.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

3. note that:

  • Good practice is to always get the current values of sound and brightness and their max values from settings to let seekbar work accordingly.
  • Above I have used two methods onProgressChanged and onStopTrackingTouch, but you can use three of them according to your need project needs.
  • Before running this, must add WRITE_SETTINGS permission in manifest.
  • you may be interested in these post on playing with settings, ENABLE/DISABLE MOBILE DATA,BLUETOOTH,AIRPLANE MODE, Change Ringer mode etc.

4. conclusion:

  • Some information about SeekBar and its usage.
  • Some information about how to set volume using Seekbar.
  • Some information about how to set Screen brightness using Seekbar.
  • Know how to use seekbar control and how to get progress values of seekbar.

    5. About the post:

    • The code seems to explain itself due to comments, but if you have any questions you can freely ask too!
    •  Don’t mind to write a comment whatever you like to ask, to know,to suggest or recommend.
    •  Hope you enjoy it!
        6. Source Code:
                you can download the source code from: GoogleDriveGithub

        Cheers,
        Hamad Ali Shaikh

        Saturday, 17 May 2014

        Change ringer Mode

        This post will describe how to set the change the properties of ringer mode using Audio manager class which help to access the ringer mode properties and allows to set the ringer mode properties i.e: (silent,vibrate,normal e.t.c). 

        Ringer Mode:

        Ringer mode is the property of android used to control ringer volume and ringer profile i-e: (silent,vibrate,Normal e.t.c) in android.

        Android Manager:

        AudioManager class provides access to these volume and ringer mode controls.

        Output:

        ringer mode ringingringer mode setting
        Create new Android Project
        Project Name: RingingMode
        //tested from 2.3.3 to current android sdk 
        Build Target: Android 2.3.3   //or greater than that
        Application Name: RingingMode
        Package Name: com.shaikhhamadali.blogspot.ringingmode
        Create Layout file: activity_main


        1. code of Layout:

        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:paddingBottom="@dimen/activity_vertical_margin"
            android:paddingLeft="@dimen/activity_horizontal_margin"
            android:paddingRight="@dimen/activity_horizontal_margin"
            android:paddingTop="@dimen/activity_vertical_margin"
            tools:context=".MainActivity" >
        
            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Set Ringer Mode" />
        
            <ImageButton
                android:id="@+id/imBtnVibrate"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/vibrate_black"
                android:text="vibrate" />
        
            <ImageButton
                android:id="@+id/imBtnSilent"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/mute_black"
                android:text="silent" />
        
            <ImageButton
                android:id="@+id/imBtnNormal"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/sound_black"
                android:text="normal" />
        
        </LinearLayout>
        

        2. code of activity:

        package com.changeringingmode;
        
        import android.app.Activity;
        import android.media.AudioManager;
        import android.os.Bundle;
        import android.view.View;
        import android.view.View.OnClickListener;
        import android.widget.ImageButton;
        import android.widget.Toast;
        
        public class MainActivity extends Activity {
         //declare views/controls 
         ImageButton imBtnVibrate,imBtnSilent,imBtnNormal;
         @Override
         protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          initializeControls();
          //initialize AudioManager
          final AudioManager audioManager = 
            (AudioManager) getSystemService(getApplicationContext().AUDIO_SERVICE);
        
          imBtnVibrate.setOnClickListener(new OnClickListener() {
        
           @Override
           public void onClick(View v) {
            //set Ringer mode as AudioManager.RINGER_MODE_VIBRATE for vibration
            audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
            //reset buttons images
            resetUI(1);
            //show toast of vibration mode
            Toast.makeText(getBaseContext(), "Mode: Vibration ", Toast.LENGTH_SHORT).show();
           }
          });
        
          imBtnSilent.setOnClickListener(new OnClickListener() {
        
           @Override
           public void onClick(View v) {
            //set Ringer mode as AudioManager.RINGER_MODE_SILENT for silent
            audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
            //reset buttons images
            resetUI(2);
            //show toast of silent mode
            Toast.makeText(getBaseContext(), "Mode: Silent ", Toast.LENGTH_SHORT).show();
           }
          });
        
          imBtnNormal.setOnClickListener(new OnClickListener() {
        
           @Override
           public void onClick(View v) {
            //set Ringer mode as AudioManager.RINGER_MODE_SILENT for silent
            audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
            //reset buttons images
            resetUI(3);
            //show toast of ringing mode
            Toast.makeText(getBaseContext(), "Mode: Ringing ", Toast.LENGTH_SHORT).show();
           }
          });
        
        
         }
        
         private void initializeControls() {
          imBtnVibrate = (ImageButton) findViewById(R.id.imBtnVibrate);
          imBtnSilent = (ImageButton) findViewById(R.id.imBtnSilent);
          imBtnNormal = (ImageButton) findViewById(R.id.imBtnNormal);
         }
        
         private void resetUI(int i) {
          if(i==1)imBtnVibrate.setImageResource(R.drawable.vibrate);
          else imBtnVibrate.setImageResource(R.drawable.vibrate_black);
          if(i==2)imBtnSilent.setImageResource(R.drawable.mute);
          else imBtnSilent.setImageResource(R.drawable.mute_black);
          if(i==3)imBtnNormal.setImageResource(R.drawable.sound_color);
          else imBtnNormal.setImageResource(R.drawable.sound_black);
         }
        }
        

        3. note that:

        • Above I have used ImageButton, to change the image on button click, image button is nothing but the combination of ImageView and Button.
        • AudioManager is not only used for ringer mode, it also handy to use for many purposes see here on develope.android.com.
        • you may be interested in these post on playing with settings, ENABLE/DISABLE MOBILE DATA,BLUETOOTH,AIRPLANE MODE etc.

        4. conclusion:

        • Some information about Ringer Mode.
        • Some information about AudioManager class and its uses.
        • Some information about ImageButton.
        • Know how to change ringer mode profile using AudioManager.

          5. About the post:

          • The code seems to explain itself due to comments, but if you have any questions you can freely ask too!
          •  Don’t mind to write a comment whatever you like to ask, to know,to suggest or recommend.
          •  Hope you enjoy it!
              6. Source Code:
                      you can download the source code from: GoogleDriveGithub

              Cheers,
              Hamad Ali Shaikh

              Thursday, 8 May 2014


              2005:

              Android is an operating system based on the Linux kernel, and designed primarily for touchscreen mobile devices such as smartphones and tablet computers. Initially developed by Android,  Inc., which Google backed financially and later bought in 2005.

              2007:

              Android was unveiled in 2007 along with the founding of the Open Handset Alliance: a consortium of hardware, software, and telecommunication companies devoted to advancing open standards for mobile devices.

              2008:

              The first Android-powered phone was sold in October 2008.The HTC Dream (also known as the T-Mobile G1 in the United States and parts of Europe, and as the Era G1 in other regions) was a smartphone developed by HTC with Google properties like Maps, Street View, Calender and Search.

              HTC dream

              Hardware: 
              3.2-inch screen (320x480), 1150 mAh battery (removable), slide-out physical keyboard, 256 MB internal storage (expandable external storage), 192 RAM, 3.2 megapixel back camera, OS Version 1.0.

              2009:
              In April 2009 first version of android was launched and named as cupcake, and then Android versions have been developed under a codename and released according to alphabetical order:
              1.  Cupcake (1.5)       April 30, 2009
              2.  Donut    (1.6)        September 15, 2009
              3.  Eclair     (2.0–2.1) October 26, 2009
              With the OS version 2.0 Eclair, The new Android Device released in market but this time it was not HTC.
              Motorola Droid
              The Motorola Droid was the first true Android smartphone to be popular with the masses. Motorola Droid released to Verizon with heavy marketing targeted at what the Droid could do that an iPhone could not, like multi-tasking.After Motorola Droid The "Droid Does" slogan became a most popular part of the geek lexicon and was Motorola's high water mark in the smartphone wars. The Device shipped with the original Android 2.0 "Eclair" version but was quickly updated to a much more stable version in Android 2.1.

              Hardware:
              3.7-inch screen (480x854), 1400 mAh battery (removable), slide-out keyboard, 512 MB internal storage (expandable external storage), 256 MB RAM, 5 MP back camera, OS Version 2.0-2.1.

              Research company Canalys estimated in the second quarter of 2009 that Android had a 2.8% share of worldwide smartphone shipments.

              Canalysis estimated in the second quarter
                 

              2010:

              In 2010, Google launched its Nexus series of devices a line of smartphones and tablets running Android operating system, and built by a manufacturing partner. HTC collaborated with Google to release the first Nexus smartphone, the Nexus One.
              Nexus One

              The Nexus One was the first Android device to serve as the flagship of the operating system released on January,5 2010 .The One was built by HTC (an altered with HTC's "Sense" skin for its Incredible smartphone) and immediately became the Popular Android smartphone on the market.
                The Nexus series has since become known as the "guide" device for new versions of the operating system.The Nexus One also marked an experiment by Google to bypass the carriers and sell directly to consumers through its website. The One was also one of the first Android smartphone to ship with Near Field Communication (NFC) functionality. This experiment did not take among consumers and most subsequent Nexus devices were offered through Google alongside subsidized versions from the likes of AT&T, T-Mobile, Verizon and Sprint. Google did not release a Nexus device for Android 2.2 because Nexus One was capable to update OS from Eclair to Froyo.
              Hardware:
              3.7-inch screen (480x800), 1400 mAh battery (removable), 512 MB internal storage (expandable), 512 MB RAM, 5 MP back camera, OS Version 2.2 Froyo.

              In the end of the year Decemeber 16, 2010, the new device was released by Samsung Nexus S.It really helped Samsung to rise in the world of smart phones by releasing the series of Samsung galaxy devices.
              Nexus s
              The Nexus S was the flagship for Android 2.3 Gingerbread, which was the most-used version of the operating system years after its release.

              Hardware:
              4-inch screen (480x800), 1500 mAh battery (removable), 16 GB internal storage, 512 MB RAM, 5 MP back camera, VGA front camera, OS Version 2.3.

              2011:

              In February 24, 2011 Android 3.2 Honeycomb was specially released to introduce the tablets interface support in Android but it didn't received good response from market as well as from developers.The only device released with this version was Motorola Xoom.
              Motorolla Xoom
               The device was released with new features like Simplified multitasking, tapping Recent Applications in the System Bar allows users to see snapshots of the tasks underway and quickly jump from one application to another and new two pane UI for contacts and email and many more.

              Hardware:
              10.1-inch screen (800x1280), 6000 mAh battery (non-removable), 32 GB internal storage, 1 GB RAM, 5 MP back camera, 2 MP front camera.OS version 3.2 Honeycomb.

              In November 17, 2011 Android 4.0  Ice Cream Sandwich was released with the rising company in the smartphones market of that time "Samsung".The device released with this version was Galaxy Nexus.
              Galaxy Nexus
              Ice Cream Sandwich update includes numerous new features.This Version includes refinements in Fonts,includes face unlock feature, ability to access applications from lock screen, hardware acceleration of UI, NFC (Near Field Communication), WIFI-Direct etc.

              Hardware:
              4.65-inch screen (720x1280), 1750 mAh battery (removable), 16/32 GB internal storage (no external memory), 1 GB RAM, 5 MP back camera, 1.3 MP front camera, OS version 4.0 Ice Cream Sandwich

              2012:

              2012 was the Lucky year for Android to cover the large amount of market with announcement of releasing tablet device with the most buttery OS Version Jelly Bean.This OS was specially designed with the primary aim of improving the functionality and performance of the user interface.In this version The performance improvement involved "Project Butter", which uses touch anticipation, triple buffering, extended vsync timing and a fixed frame rate of 60 fps to create a fluid and "buttery-smooth" UI.Android 4.1 Jelly Bean was released to the Android Open Source Project on July 9, 2012, and the Nexus 7 tablet, the first tablet to run the most buttery firmware Jelly Bean, was released on July 13, 2012.
              Nexus 7
              Hardware:
              7-inch screen (800x1280), 4325 mAh battery (non-removable), 8/16/32 GB internal memory (no external memory), 1 GB RAM, 1.2 MP front camera, OS version 4.1 Jelly Bean.

              On October 29, 2012 Google announced IO event in New York City, but the event was cancelled due to Hurricane Sandy. Instead of rescheduling the live event, Google announced the new version with a press release, under the slogan "A new flavor of Jelly Bean". Jelly Bean 4.2 the second instance of Jelly Bean (much in the same way that Android 2.0/2.1 were both Eclair).It was debuted with the Nexus 4 mobile device and Nexus 10 Tablet.
              Nexus 4
              The Nexus 4 from LG was released at the end of 2012, many people consider the Nexus 4 to be a superb instance of an Android smartphone, it was criticized for its lack of 4G LTE, of which most new smartphones have included by default. The phone was made available through Google Play store and on T-Mobile.
              Hardware:
              4.7-inch screen (768x1280), 2100 mAh battery (non-removable), 8/16 GB internal memory, 2 GB RAM, 8 MP back camera, 1.3 MP front camera, OS version 4.2 JellyBean

              And the second device released with Jelly Bean 4.2 was Samsung's Nexus 10. Samsung came back to produce the first branded large-screen (8-inches or up) Nexus tablet with the Nexus 10. The tablet was the first large screen to roll out with a flagship Android update since Motorola released the Xoom tablet with the Honeycomb release in February 2011.
              Nexus 10
              The Nexus 10 received mixed-to-favourable reviews:
              TechCrunch columnist Drew Olanoff said: Android was a better experience on a tablet than iOS and concluded "Apple has an advantage, but Google is right there on the cusp of something amazing,"
              James Rogerson of TechRadar wrote: "Ultimately, other than the price, there's little reason for Apple fans to jump ship to the Nexus 10, equally the Nexus 10 puts up enough of a defence to keep the Android faithful happy."

              Hardware:
              10-inch screen (2560×1600), 9000 mAh battery (non-removable), 16/32 GB internal memory, 2 GB RAM, 5 MP back camera, 1.9 MP front camera, OS version 4.2 JellyBean
                   

              2013:

              We can say that in 2013 Android takes the Lions share of market.According to the Strategy Analytics estimates Google’s Android platform accounted for 79% of global smartphone OS shipments in the year, It reckons a record 781.2 million smartphones shipped globally running Google’s mobile OS, out of a total of 990 million smartphones.
              On July 24, 2013 Google released Jelly Bean 4.3 under the slogan "An even sweeter Jelly Bean" during an event in San Francisco called "Breakfast with Sundar Pichai". Most Nexus devices received the update within a week, although the 2nd generation Nexus 7 tablet was the first device to officially ship with it. A minor bug fixing update was released on August 22, 2013.
              Nexus 7 second generation
              Hardware:
              7-inch screen (1920×1200), 3950 mAh battery (non-removable), 16/32 GB internal memory, 2 GB RAM, 5 MP back camera, 1.2 MP front camera, OS version 4.3 JellyBean.


              Still, returning to the smartphone market, Android remains head and shoulders above the competition and Google remains the mobile kingpin by reach.After announcing version 4.4 Kitkat on September 3, 2013.The release had long been expected by technology bloggers to be numbered 5.0 and called "Key Lime Pie".
               KitKat debuted on Google's Nexus 5 on 31 October 2013, and has been optimised to run on a greater range of devices than earlier Android versions, having 512 MB of RAM as a recommended minimum; those improvements were known as "Project Svelte" internally at Google. The required minimum amount of RAM available to Android is 340 MB, and all devices with less than 512 MB of RAM must report themselves as "low RAM" devices.
              Nexus 5 black
              Hardware:
              4.95-inch screen (1080×1920), 2300 mAh battery (non-removable), 16/32 GB internal memory, 2 GB RAM, 8 MP back camera, 1.3 MP front camera, OS version 4.4 Kitkat.

                 Android 4.4 Kitkat brought the amazing addition and that was new ART Runtime Compiler for apps that was set to replace the aging Dalvik. ART was introduced to provide potential performance boost.
              Android operating system had reached a new milestone during the third quarter of 2013 (3Q13), according to the International Data Corporation (IDC) Worldwide Quarterly Mobile Phone Tracker. With a total base of 211.6 million smartphone units shipped during the quarter, Despite high saturation rates in a number of mature markets, the overall smartphone space grew 39.9% year-over-year in the third quarter.

              On December 5, 2013 Google released version update 4.4.1 with some improvements of camera (auto focus, white balance and HDR+, Loads Google+ photos instead of gallery), Better application compatibility for the experimental ART runtime, and some miscellaneous improvements and bug fixes.
                 After four days on December 9, 2014 Google released an other version update 4.4.2 with some basic improvement like security enhancements, bug fixes and Removal of the "App Ops" application permissions control system which was introduced in Android 4.3.

              Friday, 2 May 2014


              About Text To speech:
               A text-to-speech (TTS) system converts normal language text into speech; other systems render symbolic linguistic representations like phonetic transcriptions into speech.And Android uses Text to speech engine to read text and convert into speech using downloaded language data.And i have noticed that no one tells about what are the parts of Text to speech so here is some brief info regarding parts of text to speech.

              Parts of Text To speech:

              A text-to-speech system (or "engine") is composed of two parts:

              • A Front-End

               The front-end has two major tasks. First, it converts raw text containing symbols like numbers and abbreviations into the equivalent of written-out words. This process is often called text normalization, pre-processing, or tokenization. The front-end then assigns phonetic transcriptions to each word, and divides and marks the text into prosodic units, like phrases, clauses, and sentences. The process of assigning phonetic transcriptions to words is called text-to-phoneme or grapheme-to-phoneme conversion. Phonetic transcriptions and prosody information together make up the symbolic linguistic representation that is output by the front-end.

              • A Back-End

               The back-end—often referred to as the synthesizer—then converts the symbolic linguistic representation into sound. In certain systems, this part includes the computation of the target prosody (pitch contour, phoneme durations), which is then imposed on the output speech.

              text to speech download language data

              Above popup dialog could be shown if language data is not already available on your device to download text to speech language data.so make sure that specific language data is already downloaded to your device or download it by following these steps  before using the Application.

              Settings -> Language & input -> scroll down to Text-to-speech output -> under “Preferred Engine” click the settings icon next to Google Text-to-speech Engine -> Install voice data -> select whichever language you like -> click the download icon next to the “high quality” version (should be around 240MB) -> once downloaded it should already be selected for you.

              I have used US locale so download united states voices as i used for this post.
              text to speech download US language data


              OutPut:
              text to speech on launchtext to speech changing settings

              Create new Android Project
              Project Name: TextToSpeak
              //tested from 2.3.3 to current android sdk 
              Build Target: Android 2.3.3   //or greater than that
              Application Name: TextToSpeak
              Package Name: com.shaikhhamadali.blogspot.texttospeech
              Create Layout file: activity_text_to_speech


              1. code of Layout:

              <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  xmlns:tools="http://schemas.android.com/tools"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:orientation="vertical"
                  tools:context=".TextToSpeak" >
              
                  <TextView
                      android:id="@+id/tVSpeechRate"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:text="Set Speech Rate" />
              
                  <SeekBar
                      android:id="@+id/sBSpeechRate"
                      android:layout_width="match_parent"
                      android:layout_height="wrap_content"
                      android:layout_below="@id/tVSpeechRate"
                      android:max="19"
                      android:progress="9" />
              
                  <TextView
                      android:id="@+id/tVPitchRate"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:layout_below="@id/sBSpeechRate"
                      android:text="Set Pitch" />
              
                  <SeekBar
                      android:id="@+id/sBPitchRate"
                      android:layout_width="match_parent"
                      android:layout_height="wrap_content"
                      android:layout_below="@id/tVPitchRate"
                      android:max="19"
                      android:progress="9" />
              
                  <EditText
                      android:id="@+id/eTPronounce"
                      android:layout_width="match_parent"
                      android:layout_height="wrap_content"
                      android:layout_below="@+id/sBPitchRate"
                      android:ems="10"
                      android:hint="Enter Text to Speak" >
              
                      <requestFocus />
                  </EditText>
              
                  <Button
                      android:id="@+id/btnSpeak"
                      android:layout_width="match_parent"
                      android:layout_height="wrap_content"
                      android:text="Speak" />
              
              </LinearLayout>

              2. code of activity:


              package com.shaikhhamadali.blogspot.texttospeech;
              
              import java.util.Locale;
              
              import android.os.Bundle;
              import android.app.Activity;
              import android.view.View;
              import android.view.View.OnClickListener;
              import android.widget.Button;
              import android.widget.EditText;
              import android.widget.SeekBar;
              import android.widget.SeekBar.OnSeekBarChangeListener;
              import android.widget.Toast;
              import android.speech.tts.TextToSpeech;
              
              public class TextToSpeak extends Activity implements TextToSpeech.OnInitListener{
               //Create variables
               double pitch=0.0f,speechRate=0.0f;
               //declare views/controls 
               private TextToSpeech tts;
               SeekBar sBSpeechRate,sBPitchRate;
               EditText eTPronounce;
               Button btnSpeak;
              
               @Override
               protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_text_to_speech);
                initializeControls();
                /*Initialize the Text to speech engine using the default TTS engine.
                 *This will also initialize the associated TextToSpeech engine if it isn't already running.
                 */
                tts = new TextToSpeech(this, this);
               }
               private void initializeControls() {
                //get reference of the UI Controls
                sBSpeechRate=(SeekBar)findViewById(R.id.sBSpeechRate);
                sBPitchRate=(SeekBar)findViewById(R.id.sBPitchRate);
                eTPronounce=(EditText)findViewById(R.id.eTPronounce);
                btnSpeak=(Button)findViewById(R.id.btnSpeak);
                /*initialize seek bar change listener to listen every change on seekbar
                 * either increment or decrement*/
                sBSpeechRate.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
              
                 @Override
                 public void onStopTrackingTouch(SeekBar seekBar) {}
                 @Override
                 public void onStartTrackingTouch(SeekBar seekBar) {}
                 @Override
                 public void onProgressChanged(SeekBar seekBar, int progress,
                   boolean fromUser) {
                  //divide progress by 10 to get speech rate in float values like 0.1
                  speechRate=((double)progress+1)/10;
                 }
                });
              
                sBPitchRate.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
                 @Override
                 public void onStopTrackingTouch(SeekBar seekBar) {}
                 @Override
                 public void onStartTrackingTouch(SeekBar seekBar) {}
                 @Override
                 public void onProgressChanged(SeekBar seekBar, int progress,
                   boolean fromUser) {
                  //divide progress by 10 to get pitch in float values like 0.1
                  pitch=((double)progress+1)/10;
                 }
                });
                //set default text as Welcome to shaikhhamadali.blogspot.com
                eTPronounce.setText("Welcome to shaikhhamadali.blogspot.com");
                //set on click listener to button speak call speakOut Method to speak text
                btnSpeak.setOnClickListener(new OnClickListener() {
                 @Override
                 public void onClick(View v) {
                  speakOut();
                 }
                });
               }
               @Override
               public void onInit(int status) {
                //check the status
                if (status == TextToSpeech.SUCCESS) {
                 //set language Locale to US
                 int result = tts.setLanguage(Locale.US);
                 //check that is language locale available on device or supported
                 if (result == TextToSpeech.LANG_MISSING_DATA
                   || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                 } else {
                  //then enable button to listen for listener
                  btnSpeak.setEnabled(true);
                  //and speak by calling speakOut
                  speakOut();
                 }
              
                } else {
                 //show toast if initialization failed
                 Toast.makeText(getBaseContext(), "TTS Engine Initilization Failed!",Toast.LENGTH_SHORT).show();
                }
              
               }
              
               private void speakOut() {
                //get entered text to speak
                String text = eTPronounce.getText().toString();
                //set pitch rate adjusted by user
                tts.setPitch((float)pitch);
                //set speech rate adjusted by user
                tts.setSpeechRate((float)speechRate);
                /*pass text to speak using engine and pass Queue mode as QUEUE_FLUSH where all entries in the playback queue 
                 *(media to be played and text to be synthesized) are dropped and
                 *replaced by the new entry. Queues are flushed with respect to
                 *a given calling app. Entries in the queue from other callers are not discarded*/
                tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
              
               }
               @Override
               public void onDestroy() {
                // Don't forget to stop and shutdown text to speech engine!
                if (tts != null) {
                 tts.stop();
                 tts.shutdown();
                }
                super.onDestroy();
               }
              
              }
              

              3. note that:

              • Good practice is to always shutdown text to speech engine in onDestroy.
              • Above I have used Speech Rate, speech rate is nothing but the speed of speaking text you can slow down it and can also speed it up.
              • pitch is nothing but the frequency set of voice, you can change it high and low frequency. high frequency is an example of some of the people whose voice is thinner enough to understand.
              • Learn more uses of intent voice search speech recognition and web search using intent.

              4. conclusion:

              • Some information about text to speech engine.
              • Some information pitch and speech rate setting.
              • Know how to use seek bar control and how to progress values of seek bar.
              • Know how to download text to speech engine voices of any language from settings.

                5. About the post:

                • The code seems to explain itself due to comments, but if you have any questions you can freely ask too!
                •  Don’t mind to write a comment whatever you like to ask, to know,to suggest or recommend.
                •  Hope you enjoy it!
                    6. Source Code:
                            you can download the source code from: GoogleDriveGithub

                    Cheers,
                    Hamad Ali Shaikh

                    Sunday, 27 April 2014

                    Common errors

                    Why should you know these?

                    Everyone wants to be an expert in Android development, and to be the expert in any development language you should know what kind of errors could arise and what are the reasons of errors/exceptions to solve them quickly.Also best developer is not that who has 3 to 5 years experience, but the best is that who knows what will happen if I use my logic in this way or that way, and will my logic work perfectly or it will arise some errors/exceptions.And this is the difference between Junior and Senior.Seniors predict the occurrence of errors/exceptions and avoid them using different approaches to develop applications rapidly.

                    1. Null Pointer Exception:

                    • When we use an uninitialized variable or object we are creating.
                    • When we use some layout view that is not in xml what we set in context.
                    • Calling the instance method of a null object.
                    • Accessing or modifying the field of a null object.
                    • Taking the length of null as if it were an array.
                    • Accessing or modifying the slots of null as if it were an array.
                    • Throwing null as if it were a Throw-able value. 

                    OR

                    A NULL pointer is one that points to nowhere. When you dereference a pointer "p", you say "give me the data at the location stored in "p". When p is a null pointer, the location stored in "p" is "nowhere", you're saying "give me the data at the location 'nowhere'". Obviously it can't do this, so it throws a NULL pointer exception.

                    2. Class Cast Exception:

                    • Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.
                    • Casting to the wrong type on findViewById() when getting references to the UI widgets
                    • when a program attempts to cast an object to a type with which it is not compatible. (e.g. when we try to use a linear layout which is declared as a relative layout in xml layout and vice versa).
                    • Cast the String "1" to an int=no problem but,Cast the String "abc" to an int=raises a ClassCastException

                    3. Stack Over flow Exception:

                    • It can occur in correctly written (but deeply recursive) programs. (Java and android)
                    • when a program becomes infinitely recursive.
                    • we create layout (deep and complex) that exceeds that stack of platform or virtual machine . recursive or too much of layout will create Stack overflow exception in Android also 
                      Too many inner layouts could be the reason.

                    4. Activity Not Found Exception:

                    • The activity is not declared in manifest or Forgetting to register new activities in the manifest.
                    • when you call activity and it is not present in package.

                    5. Android Security Exception:

                    • Reading data from storage and doesn't add permissions in Manifest.
                    • You need to declare all permissions in the application Manifest that your application uses (Internet, access to contact, GPS, WIFI state,write to SDCard, etc).

                    6. Out Of Memory Exception OR Monster Exception:

                    • bitmap size exceeds VM budget.
                    • when a request for memory is made that can not be satisfied using the available platform resources . mainly using high resolution images, bitmap, gallery etc.

                    7. Application Not Responding (ANR):

                    • Mainly comes when you are making network function,or some long process.this will block UI Thread so user can not do any work. to avoid ANR.

                    8. Original Thread That Created A View Hierarchy Can Touch Its Views:

                    • You must have tried to update a view content from another thread than the UI thread. So either create a handler in your UI thread and post your Runnable to this handler OR use the method runOnUIThread to run the lines of code that are doing the update.
                    9. R.layout.main Cannot Be Found/Missing:
                    • R refers to the resource file. In your source code check if you did not import android.R. An android.R import will prevent Eclipse from finding your R file. Also you can check the spelling of the xml layout file name (Here in ‘R.layout.main’, main is the layout file name) , make sure that the xml file name should not contain any space.
                    10. INSTALL_FAILED_INSUFFICIENT_STORAGE:
                    • when installing an application on emulator and emulator doesn't have storage to install application.By default Android virtual device(AVD) provides only 64M for the memory space for Android applications. You can clean your installed application by re-starting the emulator and selecting the Wipe user data flag may solve this.Also you can set the data partition size by launching AVD Manager, then if you press edit on the AVD, you can set the SD Card size.
                    So I mentioned some common errors we face while developing Android Applications that generally causes force close, so I hope that you will take care of these exceptions while developing Android applications.So try to use try - catch block in all places of program. Don't leave your catch block empty as this can hide errors:

                     try{
                        // try something
                      } catch (Exception e) {
                          Log.e("TAG", "Exception in try catch", e);
                          return false;
                      }
                      return true;

                    I think many of us have faced these exceptions,want to listen from you,have you ever faced these exceptions? 

                    Saturday, 26 April 2014

                    Device information

                    I am writing this tutorial as lot of people are asking me about how to get System properties like what is the version,Model,Hardware Manufacturer,Serial and FingerPrint of a device.As well as many of the visitors also request me to post on how to get ip4/ip6 and MAC Address of Device.
                        So Today I am creating a simple ListView to show all the list of system properties i mentioned above and a Utility class that will return an Array list of strings to load listView adapter.

                    OutPut:
                    Device informationDevice IP and MAC

                    Create new Android Project
                    Project Name: DeviceInformation
                    //tested from 2.3.3 to current android sdk 
                    Build Target: Android 2.3.3   //or greater than that
                    Application Name: DeviceInformation
                    Package Name: com.shaikhhamadali.blogspot.deviceinformation
                    Create Layout file: activity_device_info

                    1. code of Layout:


                    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                        xmlns:tools="http://schemas.android.com/tools"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        tools:context=".DeviceInfo" >
                    
                        <ListView
                            android:id="@+id/listView1"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent" >
                        </ListView>
                    
                    </RelativeLayout>

                    2. code of activity:

                    package com.shaikhhamadali.blogspot.deviceinformation;
                    
                    import android.os.Bundle;
                    import android.app.Activity;
                    import android.widget.ArrayAdapter;
                    import android.widget.ListView;
                    
                    public class DeviceInfo extends Activity {
                    
                     @Override
                     protected void onCreate(Bundle savedInstanceState) {
                      super.onCreate(savedInstanceState);
                      setContentView(R.layout.activity_device_info);
                      //Create instance of Listview and assign reference of control we declared in layout
                      ListView lv=(ListView)findViewById(R.id.listView1);
                      //create an instance of ArrayAdapter and pass context,layout,list of items
                      ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                        this, 
                        android.R.layout.simple_list_item_1,
                        Utility.getlist() );
                      //assign adapter to listview
                      lv.setAdapter(arrayAdapter); 
                     }
                    
                    }
                    

                    code of UtilityClass:


                    package com.shaikhhamadali.blogspot.deviceinformation;
                    
                    import java.util.ArrayList;
                    import java.util.List;
                    import java.net.*;
                    import java.util.*;   
                    import org.apache.http.conn.util.InetAddressUtils;
                    
                    public class Utility {
                    
                     public Utility() {
                    
                     }
                     public static ArrayList<String> getlist(){
                      //Create an instance of ArrayList of String.
                      ArrayList<String> str=new ArrayList<String>();
                      //add information to list
                      str.add("Version : "+System.getProperty("os.version"));
                      str.add("Version Release : "+android.os.Build.VERSION.RELEASE);
                      str.add("Device : "+android.os.Build.DEVICE);
                      str.add("Model : "+android.os.Build.MODEL);
                      str.add("Product : "+android.os.Build.PRODUCT);
                      str.add("Brand : "+android.os.Build.BRAND);
                      str.add("Display : "+android.os.Build.DISPLAY);
                      str.add("CPU_ABI : "+android.os.Build.CPU_ABI);
                      str.add("CPU_ABI2 : "+android.os.Build.CPU_ABI2);
                      str.add("Unknown  :"+android.os.Build.UNKNOWN);
                      str.add("HARDWARE : "+android.os.Build.HARDWARE);
                      str.add("ID : "+android.os.Build.ID);
                      str.add("Manufecturer : "+android.os.Build.MANUFACTURER);
                      str.add("Serial : "+android.os.Build.SERIAL);
                      str.add("Host : "+android.os.Build.HOST);
                      str.add("FingerPrint : "+android.os.Build.FINGERPRINT);
                      str.add("User : "+android.os.Build.USER);
                      str.add("Lan Mac Add : "+getMACAddress("wlan0"));
                      str.add("ether Add : "+getMACAddress("eth0"));
                      str.add("ipv4 : "+getIPAddress(true));
                      str.add("ipv6 : "+getIPAddress(false));
                      //return list
                      return str; 
                     }
                     /**
                       Returns MAC address of the given interface name like wlan0 or eth0.
                       @param interfaceName eth0, wlan0 or NULL=use first interface 
                       @return  mac address or empty string
                      */
                     public static String getMACAddress(String interfaceName) {
                      try {
                       //create instance of List to store List of NetworkInterfaces
                       List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
                       //iterate to every item of interfaces
                       for (NetworkInterface intf : interfaces) {
                        //check only not null interfaces
                        if (interfaceName != null) {
                         //if interface matches to the required or not 
                         if (!intf.getName().equalsIgnoreCase(interfaceName)) continue;
                        }
                        //get hardware address that is MAC address
                        byte[] mac = intf.getHardwareAddress();
                        if (mac==null) return "";
                        //create instance of StringBuilder
                        StringBuilder buf = new StringBuilder();
                        //iterate though every byte to format the address in Particular MAC address format.
                        for (int idx=0; idx<mac.length; idx++)
                         buf.append(String.format("%02X:", mac[idx]));       
                        if (buf.length()>0) buf.deleteCharAt(buf.length()-1);
                        return buf.toString();
                       }
                      } catch (Exception ex) { } // for now ignore exceptions
                      return "";
                     }
                    
                     /**
                       Get IP address from first non-localhost interface
                       @param ipv4  true=return ipv4, false=return ipv6
                       @return  address or empty string
                      */
                     public static String getIPAddress(boolean useIPv4) {
                      try {
                       //create instance of List to store List of NetworkInterfaces
                       List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
                       //iterate to every item of interfaces
                       for (NetworkInterface intf : interfaces) {
                        //create instance of List to store List of InetAddress
                        List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
                        //iterate to every item of InetAddress list
                        for (InetAddress addr : addrs) {
                         //check that is loop back address 
                         /*Valid IPv4 loopback addresses have the prefix 127/8. 
                           The only valid IPv6 loopback address is ::1.*/
                         if (!addr.isLoopbackAddress()) {
                          //get HostAddress
                          String sAddr = addr.getHostAddress().toUpperCase();
                          //check that is ipv4
                          boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                          //if ipv4 return address 
                          if (useIPv4) {
                           if (isIPv4) 
                            return sAddr;
                          } else {
                           //or ipv6 
                           if (!isIPv4) {
                            int delim = sAddr.indexOf('%'); // drop ip6 port suffix
                            //return ipv6
                            return delim<0 ? sAddr : sAddr.substring(0, delim);
                           }
                          }
                         }
                        }
                       }
                      } catch (Exception ex) { } // for now ignore Exceptions
                      return "";
                     }
                    }
                    

                    3. note that:

                    • As I ignored exceptions above but Good practice is to always check that or notify that to users regarding the problem.
                    • Above I have used NetworkInterface that represent a network interface of the local device. An interface is defined by its address and a platform dependent name. The class provides methods to get all information about the available interfaces of the system or to identify the local interface of a joined multicast group.
                    • Also InetAddress used to get the IPV4 or IPV6 of a device.
                    • You may be interested in getting paired devices listget list of sensorsListView from array and array strings.

                    4. conclusion:

                    • Some information about how to device information.
                    • Some information about how to get IP and MAC address.
                    • know how to create an Array Adapter.
                    • Know how to us NetworkInterface class and InetAddress class.

                      5. About the post:

                      • The code seems to explain itself due to comments, but if you have any questions you can freely ask too!
                      •  Don’t mind to write a comment whatever you like to ask, to know,to suggest or recommend.
                      •  Hope you enjoy it!
                          6. Source Code:
                                  you can download the source code from: GoogleDriveGithub

                          Cheers,
                          Hamad Ali Shaikh