Search This Blog

Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Wednesday, 19 April 2017

Samsung Galaxy S8 the best innovative phone in near future

Samsung is the standout performer for android O.S over the years. It’s not wrong to say that Samsung is carrying responsibility of making high end phone for android. Samsung is the only android OEM which compete with Apple on every front.

This time Samsung has again proven itself that why android is nothing without Samsung. Here are some exceptional feature which make Samsung S8, S8+ as best phone in near future



Stunning Infinity Display                              10/10


The Infinity Display sets a new standard for uninterrupted, immersive experiences. It enables an expanded screen size without necessitating a larger phone. So while the view is grander, Galaxy S8 and S8+ feel small in your hand, making them easy to hold and use.
Immerse yourself in a larger than ever screen that still fits comfortably in your hand. Galaxy S8 and S8+ break free from the confines of bezels, offering a smooth, uninterrupted surface that flows seamlessly over the edges. We achieved this by completely redesigning the phone from the inside out. And we have reinvented the home button, by placing it on the screen, where it stays hidden until you need it. So you get a bigger, unobstructed view without making the phone larger

Camera                                                        8/10


Camera comes with lots of great feature like focus on what matters, filtered moment, selfie moment. Night vision of camera is very nice. It have two mode pro and auto mode. In pro mode shutter speed, Exposure and White Balance can be customised to enhance photography experience.

Wireless Charging 


Wireless charging is another exciting feature. Even though it seems that you have to pay extra for this

Rest feature  


I don’t go into the race of upgrading Hardware (i.e. RAM, Internal Memory and processor) until software is not optimised to utilise all its resources. There are lots of phone which hung and turn slow even after having 3 GB or more RAM. Samsung has heating issue with all its previous phone. Heating issue is generally common in all phone because of steal body and compact design.


Samsung S8 is dust and water proof for 30 min which is quite long time.

I would suggest to go for it.

Wednesday, 27 July 2016

Release of Blackberry DTEK50 powered by android, survival effort

In 2010 Blackberry lost top spot to iPhone and since then only downfall of blackberry continues. There was a time when thumb injury cause by blackberry phone was named blackberry injury.
No hardware can match blackberry in the field of security. Now blackberry has decide to launch their feature combine with android o.s. being a fan of android and blackberry I am very happy to see this news. Blackberry is launching BlackBerry DTEK50.
Blackberry will possibly be lauded will latest android version Nougat.

DTEK50, The World’s Most Secure Android™ Smartphone Keeps the private details of your life safe.



Features:

Fully Android
Access to over a million apps from Google Play
5.2” scratch resistant display
Intelligent Keyboard
Convenience Key
8MP front camera with flash and 13MP auto-focus rear camera
2TB microSD card support
BlackBerry Security that protects the private details of your life from being hacked


Extra Features - BlackBerry MP-12600 Mobile Power Charger, a high capacity portable charger that powers all your mobile devices to maximize your productivity and play time.
Release date
The bundle is expected to start shipping the week of August 8th 2016

Price Estimated Total Incl. VAT: £294.58




Monday, 18 July 2016

Evolving android, points where Google android sucks because of OEM


 I was thinking a lot lately that Google is working hard to provide user a great android experience. Google is launching new fixes on monthly basis, launching a new version almost every year with ton of new features. But if we see distribution of android version over the phone market, we will be stunned by statistics. Many android customer have outdated version of android.

Some OEM believes in concept of loading hardware and software once in a lifetime like Micromax, Chinese mobile maker while most OEM only providing update to their premium phones or say flagships.

This approach is killing Google Android. I admit providing software update to existing hardware takes lot of money which OEMs don’t want to do for cheap phones. Only flagship which meant to bind with their reputation is their priority. Unlike iPhone its very hard to bring OEM and Google at same level while providing update

Look at current android distribution. Almost 70% percent of market is occupied by Kitkat and lower version of android while Google announced a new android nougat to be launch soon. I presume only some phone with Lollipop have possibility to get update of android nougat. So again the gap will only increase over the time





Who is suffering?

Obliviously android and its user are the one who suffer most by this. Android’s team hard work and latest update are not reaching to millions of users, on the hand people are willing to move but they bound by limitations of their OEM. Eventually android suffers in the whole process

Solution!

For current market strategies, competition is so high to sell devices for android manufacture that they are not going to pay attention on hardware which can support some level upgrade for new android version. Their only purpose is to sell android phone. So one solution is customer will have to buy new android phone every year.
Second possible solution is OEM should do minimum changes in android source so that they will prepare new upgrade for their existing customers at minimum cost. But this will wipe out the creativity and diversity in android market

Continue…..


Wednesday, 13 April 2016

Meet HTC 10: HTC 10 Launch, Specification, Hardware information

HTC’s new flagship phone HTC 10 is complete transition from HTC previous variant with Ultra Pixel camera, Hi-res audio and full metallic body.

HTC quote
HTC 10. It’s more of what you’re looking for in a flagship phone. Unparalleled performance. Superb 24-bit Hi-Res sound. The world’s first* Optical Image Stabilization in both front and back cameras. And one of the highest smartphone camera rankings ever from DxOMark. All in a beautifully crafted metal unibody.

HTC 10 release date and price


HTC 10 is fully launched and preorders have been started at HTC official site. But HTC 10 will take time to land in stores.


HTC's new flagship smartphone will be out on May 2016 worldwide and it will cost around US$699.99 (it’s very early estimate)

Preorder HTC 10 


Dimensions and Weight1 

145.9 x 71.9 x 3.0 - 9.0 mm, 161g
Platform Android2
Android™ 6 with HTC Sense
Main Camera
12MP (HTC UltraPixel™ 2 with 1.55μm pixel)
Laser Autofocus
BSI sensor
Optical Image Stabilisation (OIS)
Sound
HTC BoomSound™ Hi-Fi Edition
Dolby Audio™
Personal Audio Profile
Hi-Res audio certified
Hi-Res audio earphones
Display
5.2 inch, Quad HD (2560 x 1440 pixels)
Pixel density at 564 ppi (pixel per inch)
Super LCD 5
Curve edge Gorilla Glass
Display colour personalization
SIM Card Type
Nano SIM
Front Camera
5MP (1.34μm pixels)
Autofocus
BSI sensor
Optical Image Stabilisation (OIS)
Battery and Charging Speed5
Capacity: 3000 mAh
Talk time on 3G/4G network: up to 27 hours
Standby time on 3G/4G network: up to 19 days
Power saving mode
Extreme power saving mode
Quick Charge 3.0 with cool charge
Up to 50% charge in 30 min
CPU Speed
Qualcomm® Snapdragon™ 820, Quad Core, 64bit, up to 2.2GHz
Memory3
ROM: 32GB / RAM: 4GB
Available storage for users: about 23GB
Extended memory: microSD™ up to 2TB
Flex Storage supported






Wednesday, 14 January 2015

Android Memory optimization tips and tricks

Android central process Zygote forked to allocate memory for every other process. Because of limited resource in mobile, memory optimization is necessary in android. Don't ask for more memory if you don't require it. Here are some tips which will help running your application smoothly


  • Enums often require more than twice as much memory as static constants. You should strictly avoid using enums on Android.
  • Every class in Java (including anonymous inner classes) uses about 500 bytes of code.  and every class instance has 12-16 bytes of RAM overhead.
  • Putting a single entry into a HashMap requires the allocation of an additional entry object that takes 32 bytes 
  • Use optimized container from android framework like  SparseArray, SparseBooleanArray, and LongSparseArray. generic HashMap use can be quite memory inefficient because it needs a separate entry object for every mapping so use  SparseArray.
  • Release memory as memory becomes tight 
  • onTrimMemory() callback of Activity help you finding way to release resource. Callbacks like TRIM_MEMORY_RUNNING_LOW, TRIM_MEMORY_RUNNING_MODERATE, TRIM_MEMORY_RUNNING_CRITICAL etc gives you way to release unused resource which eventually help improving performance of your app
  • Load views on demand using ViewStub read about ViewStub
  • Use multiple process in a single application. Name your background services as separate process like 

         <service android:name=".PlaybackService" android:process=":background" />

Thursday, 1 January 2015

Happy new year, Meaning of newly born 2015 for android developer

This is my first article of newly born 2015. First of all i wish a very happy and safe 2015 to reader. Today i choose to right about my own judgement, suggestion and prediction for android developer. Never forgot to tell me at end of the article how much i went correct?

More tough competition to survive

Lot of big player had joined android success ride.Day by day, Google play is flooded with thousand of quality android application daily.Getting attention is going stiff unless you have not made something really great. For small and individual developer, this is more tough to survive now.We should thanks to Google search strategies on play store which indeed a help to developer. Success mantra is keep growing your creativity.


Android wear will be strong

Developing app for android wear will be a good option. Keeping vision in information technology is best way to survive.Android Wear was announced and launched in 2014. We saw some great devices from the usual suspects (Samsung, LG, Motorola)


Keep an eye on CyanogenMod and Tizen

CyanogenMod is highly customize android by some enthusiastic developer community. For techgeek it will be a great option to have in their device. CyanogenMod has potential and its hardly take days for android developer to make application for CyanogenMod. Keep posting your ideas for Tizen too.
Samsung had created user sector all over the world and you can't ignore Korean giants.


Give a chance to amazon developer console

Most of the android application run on amazon devices with no or less modification. Give it a chance, that will surely increase your earnings. Amazon provide you amazing test framework which will help you building quality application.


Don't tease ios Developer

Last but not leaset, Being human you should respect a human so as being developer you should respect developer. 2015 will not gonna downfall of apple. iPhone 6+ advance
booking shows craze of iPhone lover.

Friday, 5 December 2014

WRITE_EXTERNAL_STORAGE permision limit to primary memory acess : Weirdest update of Android KitKat 4.4

Post Address Issue -


  • WRITE_EXTERNAL_STORAGE  doesn't work with Android KitKat 4.4
  • Android KitKat 4.4 doesn't allowing writing to secondary storage
  • Error accessing the SD card on Android KitKat (4.4.x)

I had gone through Weirdest  issue recently, My app suddenly got bad reviews as  app is not working with Android KitKat 4.4 and above. I dig out and find problem, My android application was not able to read from android secondry memory storage (i.e called Sdcard also.). Android KitKat 4.4 support WRITE_EXTERNAL_STORAGE  in certain manner now.

Interesting point for KitKat is that writing to secondary external storage (such as SD memory card) is prohibited, except of app's specific directory, which is deleted during app uninstall.Only solution to this problem is to get your phone rooted.

Google Android cleary says


The WRITE_EXTERNAL_STORAGE permission must only grant write access to the primary external storage on a device. Apps must not be allowed to write to secondary external storage devices, except in their package-specific directories as allowed by synthesized permissions. Restricting writes in this way ensures the system can clean up files when applications are uninstalled.

If your phone is rooted you will have access to /system/etc/security/permissions.xml . media_rw is clearly missing here

<permission name="android.permission.WRITE_EXTERNAL_STORAGE" >
<group gid="sdcard_r" />
<group gid="sdcard_rw" />
<group gid="media_rw" />
</permission>

still its not clear why Google android KitKat 4.4 has logic behind this Weirdest . See Reported BUG to Android 4.4 does not allowing writing to secondary storage.

Thursday, 4 December 2014

Moto G first generation will get Android Lollipop update soon From Motorola Offcial Blog

Motorola had confirm upgrade of Android Lollipop to Moto G first generation. And it should start rolling out very soon according to Motorola news. Motorola other phone Moto G second generation and Moto X are already start getting upgrade to Android L. Android Lollipop is latest version launch by Google Android.

GSM Arena stated
Well, it seems they won't have to wait too long. Motorola has updated the Motorola Update Services app on the first generation Moto G. If you check the change log for the app, it simply says 'This update is necessary to enable a future upgrade of your device to Android 5.0, Lollipop.
Its seems that User will start getting upgrade in mid December.
                  

Motorola is very quick in providing latest update to its user. Motorola promise Android Lollipop upgrade to below devices.

  •     Moto X (1st Gen. & 2nd Gen.)
  •     Moto G (1st Gen. & 2nd Gen.)
  •     Moto G with 4G LTE
  •     Moto E
  •     Droid Ultra, Droid Maxx, and Droid Mini


Tuesday, 2 December 2014

WebView Scroll Vertically : WebView scroll in one direction after zoom in android

Android WebView allow to load HTML content. Recently i was facing issue regarding zoom of WebView. What my requirement was, for scroll WebView content vertically regardless of its zoom level. Simply i want to stop horizontal scroll of webview.
I came across meta tag ViewPort and it did a lot of help with some attribute of WebSettings dynamically.

  • Wrap WebView inside ScrollView
  • Meta Tag viewport : Attach this meta tag immediately after <head>

<meta name="viewport" content="width=device-width,height=device-height,target-densityDpi=device-dpi,user-scalable=yes,initial-scale=0.5, maximum-scale=2, minimum-scale=0.5" />

If you don't have control on HTML content, then read HTML content in one string and then append above tag and then write to file again or use with webview's method loadwithBaseURL

StringBuilder mBuilder = new StringBuilder(mBuffer.toString().replace("<head>",
"<head><meta name=\"viewport\" content=\"width=device-width,height=device-height,target-densityDpi=device-dpi,user-scalable=yes,initial-scale=0.5, maximum-scale=2, minimum-scale=0.5\" />"));

mBuffer is the HTML string. you can change WebView's scale according to requirement

  • Attribute need to set dynamically are 

view.getSettings().setLoadWithOverviewMode(true);
view.getSettings().setUseWideViewPort(true);
view.setWebChromeClient(webChromeClient);
view.getSettings().setBuiltInZoomControls(true);
view.getSettings().setSupportZoom(true);

where view is reference of WebView.

Achieve Through this Article 

  •  Content will fit to new line to scroll WebView only vertically
  •  Fit content to initial scale using Meta Viewport
  • Content will not go more than WebView width




Wednesday, 28 May 2014

PHILIPS W6610 5300 mAh Battery ! A smart phone with best battery is launched

Smart phone had many thing which drain battery and leaving those thing behind does not give feel of smart phone. Running apps all the time (like Whatsapp, Facebook and weather services), HD display and many more cause battery to die. So anticipation of user were battery to invent to next level and PHILIPS did it. It launched PHILIPSW6610 with 5300 mAh battery which best till date.
Bigger battery strength make phone thicker compare to its competitor but you can enjoy Standby time: 1604 hrs (WCDMA+GSM) and Talk time: 33 hrs (WCDMA). PHILIPSW66 run on android version Jelly Bean (4.2) and PHILIPS does not reveal about up gradation weather they are going to update to latest version or not. It will cost around Rs.20,262.00 or $340 (Approx).



PHILIPSW66 launched with 1 GB RAM, 1.3 GHZ quad core processor. The smartphone packs a 5-inch display with qHD resolution (960 x 540) 4GB of internal memory, microSD support, dual SIM support and Android 4.2 Jelly Bean.

Saturday, 30 November 2013

Download file (Video/Audio/text) through android WebView

Android WebView happy go tool for cross development of android application like PhoneGap and jQuery mobile. Few days ago i found in situation where i need to download some file while clicking on button inside WebView . I search a lot on Google and found some solution which lead me to fix issue. StackOverflow plays an vital role in this. Now i upgrade my solution using download manager. DownloadManger will manage download automatically. Read communication between android and JavaScript

Permission required for this application

   <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />  
   <uses-permission android:name="android.permission.INTERNET" />  
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  

You can download any kind of data through this code only you need to change your file extension.

Now create one WebView

           WebView webview = new WebView(this);  
           webview.setWebChromeClient(new WebChromeClient());  
           WebViewClient client = new ChildBrowserClient();  
           webview.setWebViewClient(client);  
           WebSettings settings = webview.getSettings();  
           settings.setJavaScriptEnabled(true);  
           webview.setInitialScale(1);  
           webview.getSettings().setUseWideViewPort(true);  
           settings.setJavaScriptCanOpenWindowsAutomatically(false);  
           settings.setBuiltInZoomControls(true);  
           settings.setPluginState(PluginState.ON);  
           settings.setDomStorageEnabled(true);  
           webview.loadUrl("yoursideurl");  
           webview.setId(5);  
           webview.setInitialScale(0);  
           webview.requestFocus();  
           webview.requestFocusFromTouch();  
           setContentView(webview);  

Most importantly WeViewClient allow you handle url and bypass them if they do not contain media(video/image)

      /**  
       * The webview client receives notifications about appView  
       */  
      public class ChildBrowserClient extends WebViewClient {  
           @SuppressLint("InlinedApi")  
           @Override  
           public boolean shouldOverrideUrlLoading(WebView view, String url) {  
                boolean value = true;  
                String extension = MimeTypeMap.getFileExtensionFromUrl(url);  
                if (extension != null) {  
                     MimeTypeMap mime = MimeTypeMap.getSingleton();  
                     String mimeType = mime.getMimeTypeFromExtension(extension);  
                     if (mimeType != null) {  
                          if (mimeType.toLowerCase().contains("video")  
                                    || extension.toLowerCase().contains("mov")  
                                    || extension.toLowerCase().contains("mp3")) {  
                               DownloadManager mdDownloadManager = (DownloadManager) DownloadWebview.this  
                                         .getSystemService(Context.DOWNLOAD_SERVICE);  
                               DownloadManager.Request request = new DownloadManager.Request(  
                                         Uri.parse(url));  
                               File destinationFile = new File(  
                                         Environment.getExternalStorageDirectory(),  
                                         getFileName(url));  
                               request.setDescription("Downloading via Your app name..");  
                               request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);  
                               request.setDestinationUri(Uri.fromFile(destinationFile));  
                               mdDownloadManager.enqueue(request);  
                               value = false;  
                          }  
                     }  
                     if (value) {  
                          view.loadUrl(url);  
                     }  
                }  
                return value;  
           }  
           @Override  
           public void onPageFinished(WebView view, String url) {  
                super.onPageFinished(view, url);  
           }  
           /**  
            * Notify the host application that a page has started loading.  
            *   
            * @param view  
            *      The webview initiating the callback.  
            * @param url  
            *      The url of the page.  
            */  
           @Override  
           public void onPageStarted(WebView view, String url, Bitmap favicon) {  
                super.onPageStarted(view, url, favicon);  
           }  
      }  
      /**  
       * File name from URL  
       *   
       * @param url  
       * @return  
       */  
      public String getFileName(String url) {  
           String filenameWithoutExtension = "";  
           filenameWithoutExtension = String.valueOf(System.currentTimeMillis()  
                     + ".mp4");  
           return filenameWithoutExtension;  
      }  

I had written the download Manage code their in above lines. In which you have to give your destination local file in which you want to save it.

Now look at the whole class code

 import java.io.File;  
 import android.annotation.SuppressLint;  
 import android.app.Activity;  
 import android.app.DownloadManager;  
 import android.content.Context;  
 import android.graphics.Bitmap;  
 import android.net.Uri;  
 import android.os.Bundle;  
 import android.os.Environment;  
 import android.webkit.MimeTypeMap;  
 import android.webkit.WebChromeClient;  
 import android.webkit.WebSettings;  
 import android.webkit.WebSettings.PluginState;  
 import android.webkit.WebView;  
 import android.webkit.WebViewClient;  
 public class DownloadWebview extends Activity {  
      @SuppressWarnings("deprecation")  
      @SuppressLint("SetJavaScriptEnabled")  
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           WebView webview = new WebView(this);  
           webview.setWebChromeClient(new WebChromeClient());  
           WebViewClient client = new ChildBrowserClient();  
           webview.setWebViewClient(client);  
           WebSettings settings = webview.getSettings();  
           settings.setJavaScriptEnabled(true);  
           webview.setInitialScale(1);  
           webview.getSettings().setUseWideViewPort(true);  
           settings.setJavaScriptCanOpenWindowsAutomatically(false);  
           settings.setBuiltInZoomControls(true);  
           settings.setPluginState(PluginState.ON);  
           settings.setDomStorageEnabled(true);  
           webview.loadUrl("yoursideurl");  
           webview.setId(5);  
           webview.setInitialScale(0);  
           webview.requestFocus();  
           webview.requestFocusFromTouch();  
           setContentView(webview);  
      }  
      /**  
       * The webview client receives notifications about appView  
       */  
      public class ChildBrowserClient extends WebViewClient {  
           @SuppressLint("InlinedApi")  
           @Override  
           public boolean shouldOverrideUrlLoading(WebView view, String url) {  
                boolean value = true;  
                String extension = MimeTypeMap.getFileExtensionFromUrl(url);  
                if (extension != null) {  
                     MimeTypeMap mime = MimeTypeMap.getSingleton();  
                     String mimeType = mime.getMimeTypeFromExtension(extension);  
                     if (mimeType != null) {  
                          if (mimeType.toLowerCase().contains("video")  
                                    || extension.toLowerCase().contains("mov")  
                                    || extension.toLowerCase().contains("mp3")) {  
                               DownloadManager mdDownloadManager = (DownloadManager) DownloadWebview.this  
                                         .getSystemService(Context.DOWNLOAD_SERVICE);  
                               DownloadManager.Request request = new DownloadManager.Request(  
                                         Uri.parse(url));  
                               File destinationFile = new File(  
                                         Environment.getExternalStorageDirectory(),  
                                         getFileName(url));  
                               request.setDescription("Downloading via Your app name..");  
                               request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);  
                               request.setDestinationUri(Uri.fromFile(destinationFile));  
                               mdDownloadManager.enqueue(request);  
                               value = false;  
                          }  
                     }  
                     if (value) {  
                          view.loadUrl(url);  
                     }  
                }  
                return value;  
           }  
           @Override  
           public void onPageFinished(WebView view, String url) {  
                super.onPageFinished(view, url);  
           }  
           /**  
            * Notify the host application that a page has started loading.  
            *   
            * @param view  
            *      The webview initiating the callback.  
            * @param url  
            *      The url of the page.  
            */  
           @Override  
           public void onPageStarted(WebView view, String url, Bitmap favicon) {  
                super.onPageStarted(view, url, favicon);  
           }  
      }  
      /**  
       * File name from URL  
       *   
       * @param url  
       * @return  
       */  
      public String getFileName(String url) {  
           String filenameWithoutExtension = "";  
           filenameWithoutExtension = String.valueOf(System.currentTimeMillis()  
                     + ".mp4");  
           return filenameWithoutExtension;  
      }  
 }  



Monday, 25 November 2013

how to disable nested ViewGroup's (RelativeLayout,LinearLayout etc) childs android

This is tutorial is a part android Utility functions, ViewGroup, View disable and enable

I created one function for disabling all View of any child whether its LinearLayout, RelativeLayout or anything. It will go through complete View Hierarchy and will disable all View contains inside parent. This function call recursive and work even if ViewGroup contains another ViewGroup too.
Enjoy by running it

    public void disableAllSettings(ViewGroup mGroup) {

        int itotal = mGroup.getChildCount();
        for (int i = 0; i < itotal; i++) {
            if (mGroup.getChildAt(i) instanceof ViewGroup) {
                disableAllSettings((ViewGroup) mGroup.getChildAt(i));
            } else {
                mGroup.getChildAt(i).setEnabled(false);
            }
        }
    }

Monday, 22 July 2013

Sound Pool Tutorial in Android : changing pitch of an sound file

SoundPool provide a frequency range to change the pitch of voice. This tutorial address the sound pool features. After reading this tutorial you will be able to answer these question

1) What is soundPool?
2) Why we use it?
3) How to change pitch of sound file through frequency?

How to prepare a simple sound Pool?


Sound Pool : A SoundPool is a collection of samples that can be loaded into memory from a resource inside the APK or from a file in the file system. The SoundPool library uses the MediaPlayer service to decode the audio into a raw 16-bit PCM mono or stereo stream. This allows applications to ship with compressed streams without having to suffer the CPU load and latency of decompressing during playback.

Creating simple sound pool with one sound file. Keep your sound file inside raw folder

SoundPool soundPool = new SoundPool(50, AudioManager.STREAM_MUSIC, 0);

50 is the number of repeat cycle, 0 is srcquality

Now load one sound file and wait until load finish using OnLoadCompleteListener.

        /** Sound ID for Later handling of sound pool **/
        soundId = soundPool.load(this, R.raw.sounds, 1);
        soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool arg0, int arg1, int arg2) {
                streamId = soundPool.play(soundId, 1, 1, 1, 3, pitch);
                soundPool.setLoop(streamId, -1);
                Log.e("TAG", String.valueOf(streamId));
            }
        });

This tutorial has two button two increase and decrease frequency rate. Just See the complete code

XML


<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=".PitchActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="147dp"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/plus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginLeft="147dp"
        android:layout_marginTop="35dp"
        android:text="+" />

    <Button
        android:id="@+id/minus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/plus"
        android:layout_below="@+id/plus"
        android:layout_marginTop="41dp"
        android:text="-" />

</RelativeLayout>

Activity


package com.pitch;

import android.app.Activity;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class PitchActivity extends Activity implements OnClickListener {
    TextView mtxView;
    SoundPool soundPool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pitch);
        mtxView = (TextView) findViewById(R.id.textView1);
        mtxView.setText("Current Pitch=0.5");
        findViewById(R.id.plus).setOnClickListener(this);
        findViewById(R.id.minus).setOnClickListener(this);
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        soundPool = new SoundPool(50, AudioManager.STREAM_MUSIC, 0);
        /** Sound ID for Later handling of sound pool **/
        soundId = soundPool.load(this, R.raw.sounds, 1);
        soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool arg0, int arg1, int arg2) {
                streamId = soundPool.play(soundId, 1, 1, 1, 3, pitch);
                soundPool.setLoop(streamId, -1);
                Log.e("TAG", String.valueOf(streamId));
            }
        });
    }

    int streamId = 0;
    int soundId = -1;
    float pitch = 01f;

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
        case R.id.minus:
            pitch -= 0.5;
            mtxView.setText("Current Pitch=" + pitch);
            soundPool.setRate(streamId, pitch);
            break;
        case R.id.plus:
            pitch += 0.5;
            mtxView.setText("Current Pitch=" + pitch);
            soundPool.setRate(streamId, pitch);
            break;
        default:
            break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            soundPool.pause(streamId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}



Important Points : your file not be bigger than 32 because Android Audio Framework allows only 32 tracks(includes playing/stopped/paused/...) per mixer thread at the same time. If it exceed then you will get error code -12

AudioFlinger could not create track, status: -12
Error creating AudioTrack

Reference Link

Android Developer

Saturday, 1 June 2013

Android action bar style generator

Action bar becomes popular after it launched in android 3.1 version. Using action with Fragment avoid overhead of maintaining stack of activity. But customizing action bar style is pain. We should thank to Jeff Gilfelt  for his great work. He provide tool of customizing action in unique style.
Just customize action bar style like editing a photo in Photo Editor and it will provide you complete resource with layout, style and draw-able (which include hdpi, ldpi and xhdpi images)

You can use Sherlock Action bar also if you have backward compatibility issue. You can customize its look and feel.

It provide you complete control on customization on android action bar style. you can change action bar Tab bottom line and all other thing related to it

Here Go for Action Bar Style Customization URL

Sunday, 12 May 2013

Android Download Manager Example , Controlling download in android application

Android provide download manager to download different kind of data. Download Manager make developer life much easier. Handling download becomes very easy.
DownloadManager class support only after API 9

Implementing DownloadManager is easy. Lets have a look how we can start downloading using DownloadManager  in android application

    /**
     * Start Download
     */
    public void startDownload() {
        DownloadManager mManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        Request mRqRequest = new Request(
                Uri.parse("http://androidtrainningcenter.blogspot.in/2012/11/android-webview-loading-custom-html-and.html"));
        mRqRequest.setDescription("This is Test File");
//        mRqRequest.setDestinationUri(Uri.parse("give your local path"));
        long idDownLoad=mManager.enqueue(mRqRequest);
    }



Request mRqRequest = new Request(
Uri.parse("http://androidtrainningcenter.blogspot.in/2012/11/android-webview-loading-custom-html-and.html")); allow you request from DownloadManager to start downloading. You can set your custom Description using Request class.

Handling Download : Stopping, Removing and opening download file

When you start download request, it return you one id. Application can handle download using that id

long idDownLoad=mManager.enqueue(mRqRequest);
mManager.remove(idDownLoad);
try {
mManager.openDownloadedFile(idDownLoad);
} catch (FileNotFoundException e) {
e.printStackTrace();
}

Catching Action Using BroadCastReceiver And Notify User

Take on BroadCastReceiver and Register it. You will ACTION_DOWNLOAD_COMPLETE if application register this Intent-Filter.

    DownLoadComplte mDownload;

    @Override
    protected void onStart() {
        super.onStart();
        mDownload = new DownLoadComplte();
        registerReceiver(mDownload, new IntentFilter(
                DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mDownload);
    }

    private class DownLoadComplte extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equalsIgnoreCase(
                    DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                Toast.makeText(context, "Download Complte", Toast.LENGTH_LONG)
                        .show();
            }
        }
    }

Viewing your downloaded File


public void viewDownload() {
Intent mView = new Intent();
mView.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(mView);
}

Wednesday, 24 April 2013

Android Reverse Geo Coding : Getting Human Readable address from latitude and longitude in android

We can show any address on map using latitude and longitude. But showing number rather than any useful information make no sense for any user. Reverse Geo Coding is process to convert latitude and longitude into one readable address in the form of String

     public String getAddress(Activity acLocal) {
 String address="";
       Geocoder geocoder;
        List<Address> addresses = null;
        geocoder = new Geocoder(_acLocal, Locale.getDefault());
        try {
            addresses = geocoder.getFromLocation(lat, longi, 1);

            String address = addresses.get(0).getAddressLine(0);
            String city = addresses.get(0).getAddressLine(1);
            String country = addresses.get(0).getCountryName();
            address = Html.fromHtml(
                    address + "<br>" + city + "<br>" + country).toString();
        } catch (Exception e) {
            e.printStackTrace();
            address = Html.fromHtml("<br>&nbsp;Unable to get any address.")
                    .toString();
        }
       return address;
} 

It will give you available address for respective latitude and longitude. Throws an exception if not able to convert into address

Saturday, 20 April 2013

Removing status bar notification from android application

Status bar notification used to show some important alert from in or outside the application in android. See Creating Simple notification is simple. This tutorial address the issue of removing notification from status bar while you are inside the application. Its easy to remove when you get involve with notification (like touch) but we will learn today how can we remove them without touch or involving with them Main concept run around notification id. You can remove any notification from anywhere if you notification id. So we need one data base to store id of notification while we generate this and later on remove notification


Steps 

Step 1) Required a simple user Interface with one button to generate notification and one to remove it. Create remove.xml 

<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=".NotificationRemove" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="14dp"
        android:text="Send Notification" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="79dp"
        android:text="Clear Notification" />

</RelativeLayout>

Notification
                                           
Step 2) Create a simple data base class DataBase.java to store the notification id

package com.notificationremoval;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBase extends SQLiteOpenHelper {

    public static final String tName = "tName";
    public static final String mNotiID = "mNotiID";

    public DataBase(Context context) {
        super(context, "temp.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String mNotifi = "create table noti(noti_id integer not null);";
        db.execSQL(mNotifi);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

}


Step 3) Now create one Activity that Handle removal of notification


package com.notificationremoval;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

public class NotificationRemove extends Activity implements OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.remove);
        findViewById(R.id.button1).setOnClickListener(this);
        findViewById(R.id.button2).setOnClickListener(this);
    }

    private void createAndGenerateNotifcation() {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                this).setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("Notification TItile").setContentText("Body");
        mBuilder.setAutoCancel(true);
        Intent resultIntent = new Intent();
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addNextIntent(resultIntent);
        int noti_id = (int) System.currentTimeMillis();
        insertNotifi(noti_id);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(noti_id, mBuilder.build());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button1:
            createAndGenerateNotifcation();
            break;
        case R.id.button2:
            RemoveAllNotification();
            break;
        }
    }

    public void RemoveAllNotification() {
        DataBase mBase = new DataBase(this);
        Cursor cur = mBase.getWritableDatabase().query("noti", null, null,
                null, null, null, null, null);
        cur.moveToFirst();
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        do {
            int id = cur.getInt(0);
            mNotificationManager.cancel(id);
        } while (cur.moveToNext());
        try {
            cur.close();
        } catch (Exception e) {
        }
    }

    public void insertNotifi(int id) {
        DataBase mBase = new DataBase(this);
        ContentValues cVales = new ContentValues();
        cVales.put("noti_id", id);
        SQLiteDatabase db = mBase.getWritableDatabase();
        long i = db.insert("noti", null, cVales);
        Log.i("Insert", String.valueOf(i));
        try {
            db.close();
        } catch (Exception e) {
        }
    }

}


Enjoy and keep commenting

Saturday, 6 April 2013

Update Pinch to zoom example and tutorial for android ImageView with zoom limit

I wrote on the same topic Pinch to zoom in android ImageView while i just started blogging. And that still is my one of the popular article, despite that it has many complication and limitation with it. So i am working to improve it. After reading most comment, I feel some problems while implementing pinch to zoom with android ImageView using previous post
  • How to implement that pinch to zoom in their project? 
  • Determining Zoom limit in pinch to zoom ImageView! 
  • Does not work properly as i told in post !! 

So now i come up with a solution in which every drawback avoided and pinch to zoom image in android seems quite simple and work perfect
Follows thes easy steps

1) Create a new project and Download this library , add this Jar to libs folder of your project 

2) Create one layout with one ImageView (Which need to be zoom)

3) Create one Activity and change to following code. This will handle all attributes required for pinch to zoom ImageView


import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import com.imagezoom.ImageAttacher;
import com.imagezoom.ImageAttacher.OnMatrixChangedListener;
import com.imagezoom.ImageAttacher.OnPhotoTapListener;

public class SampleZoom extends Activity {
    ImageView mImaView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pinch_sample);
        mImaView = (ImageView) findViewById(R.id.simple);

        Bitmap bimtBitmap = BitmapFactory.decodeResource(getResources(),
                R.drawable.a);
        mImaView.setImageBitmap(bimtBitmap);

        /**
         * Use Simple ImageView
         */
        usingSimpleImage(mImaView);

    }

    public void usingSimpleImage(ImageView imageView) {
        ImageAttacher mAttacher = new ImageAttacher(imageView);
        ImageAttacher.MAX_ZOOM = 2.0f; // Double the current Size
        ImageAttacher.MIN_ZOOM = 0.5f; // Half the current Size
        MatrixChangeListener mMaListener = new MatrixChangeListener();
        mAttacher.setOnMatrixChangeListener(mMaListener);
        PhotoTapListener mPhotoTap = new PhotoTapListener();
        mAttacher.setOnPhotoTapListener(mPhotoTap);
    }

    private class PhotoTapListener implements OnPhotoTapListener {

        @Override
        public void onPhotoTap(View view, float x, float y) {
        }
    }

    private class MatrixChangeListener implements OnMatrixChangedListener {

        @Override
        public void onMatrixChanged(RectF rect) {

        }
    }
}

Implementing Zoom Limit. 


See inside function usingSimpleImage(), below two line decide zoom limit ImageAttacher.MAX_ZOOM = 2.0f;  // Double the current Size ImageAttacher.MIN_ZOOM = 0.5f; // Half the current Size

Note : Work perfect for the image with fit width (either in Landscape or portrait)

Tuesday, 26 March 2013

How to make ListView Divider transparent in android?

ListView has strong support for customizaton. Generally, we need customize divider in listview to seprate each row. But some times we need divider with transparency. Divider occupies the place but with no backrgound, it seems like transparent space between the rows of ListView.
 
mListView.setDividerHeight(10);
mListView.setDivider(getResources().getDrawable(android.R.color.transparent));

mListView is the instance of ListView. These two line will create divider with white space

Wednesday, 13 March 2013

Binding service using Android Interface DefinitionLanguage (.aidl) in android

Binding service using iBinder an Messanger already discussesd. Third and most complicated way is binding service using Android Interface Definition Language (AIDL). Its rarely use and hard to implement. So this post simply will show you how to create one connection using Android Interface Definition Language (AIDL) between activity and service

 When to use Android Interface Definition Language (AIDL)

Using AIDL is necessary only if you allow clients from different applications to access your service for IPC and want to handle multithreading in your service. If you do not need to perform concurrent IPC across different applications, you should create your interface by implementing a Binder or, if you want to perform IPC, but do not need to handle multithreading, implement your interface using a Messenger. Knowledge Required you should read about binding service using IBinder and Messanger

 Steps 1) create .aidl interface. Create one file name IRemoteService.aidl and keep inside your main package


 // IRemoteService.aidl  
 package com.example.locationmanager;  
 // Declare any non-default types here with import statements  
 /** Example service interface */  
 interface IRemoteService {  
 /** Request the process ID of this service, to do evil things with it. */  
 int getPid();  
 /** Demonstrates some basic types that you can use as parameters  
 * and return values in AIDL.  
 */  
 void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,  
 double aDouble, String aString);  
 }  

When you build your application IRemoteService.aidl changes into IRemoteService.java like this. You can find this inside bin folder

 // Declare any non-default types here with import statements  
 /** Example service interface */  
 public interface IRemoteService extends android.os.IInterface {  
 /** Local-side IPC implementation stub class. */  
 public static abstract class Stub extends android.os.Binder implements  
 com.example.locationmanager.IRemoteService {  
 private static final java.lang.String DESCRIPTOR = "com.example.locationmanager.IRemoteService";  
 /** Construct the stub at attach it to the interface. */  
 public Stub() {  
 this.attachInterface(this, DESCRIPTOR);  
 }  
 /**  
 * Cast an IBinder object into an  
 * com.example.locationmanager.IRemoteService interface, generating a  
 * proxy if needed.  
 */  
 public static com.example.locationmanager.IRemoteService asInterface(  
 android.os.IBinder obj) {  
 if ((obj == null)) {  
 return null;  
 }  
 android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);  
 if (((iin != null) && (iin instanceof com.example.locationmanager.IRemoteService))) {  
 return ((com.example.locationmanager.IRemoteService) iin);  
 }  
 return new com.example.locationmanager.IRemoteService.Stub.Proxy(  
 obj);  
 }  
 @Override  
 public android.os.IBinder asBinder() {  
 return this;  
 }  
 @Override  
 public boolean onTransact(int code, android.os.Parcel data,  
 android.os.Parcel reply, int flags)  
 throws android.os.RemoteException {  
 switch (code) {  
 case INTERFACE_TRANSACTION: {  
 reply.writeString(DESCRIPTOR);  
 return true;  
 }  
 case TRANSACTION_getPid: {  
 data.enforceInterface(DESCRIPTOR);  
 int _result = this.getPid();  
 reply.writeNoException();  
 reply.writeInt(_result);  
 return true;  
 }  
 case TRANSACTION_basicTypes: {  
 data.enforceInterface(DESCRIPTOR);  
 int _arg0;  
 _arg0 = data.readInt();  
 long _arg1;  
 _arg1 = data.readLong();  
 boolean _arg2;  
 _arg2 = (0 != data.readInt());  
 float _arg3;  
 _arg3 = data.readFloat();  
 double _arg4;  
 _arg4 = data.readDouble();  
 java.lang.String _arg5;  
 _arg5 = data.readString();  
 this.basicTypes(_arg0, _arg1, _arg2, _arg3, _arg4, _arg5);  
 reply.writeNoException();  
 return true;  
 }  
 }  
 return super.onTransact(code, data, reply, flags);  
 }  
 private static class Proxy implements  
 com.example.locationmanager.IRemoteService {  
 private android.os.IBinder mRemote;  
 Proxy(android.os.IBinder remote) {  
 mRemote = remote;  
 }  
 @Override  
 public android.os.IBinder asBinder() {  
 return mRemote;  
 }  
 public java.lang.String getInterfaceDescriptor() {  
 return DESCRIPTOR;  
 }  
 /**  
 * Request the process ID of this service, to do evil things with  
 * it.  
 */  
 @Override  
 public int getPid() throws android.os.RemoteException {  
 android.os.Parcel _data = android.os.Parcel.obtain();  
 android.os.Parcel _reply = android.os.Parcel.obtain();  
 int _result;  
 try {  
 _data.writeInterfaceToken(DESCRIPTOR);  
 mRemote.transact(Stub.TRANSACTION_getPid, _data, _reply, 0);  
 _reply.readException();  
 _result = _reply.readInt();  
 } finally {  
 _reply.recycle();  
 _data.recycle();  
 }  
 return _result;  
 }  
 /**  
 * Demonstrates some basic types that you can use as parameters and  
 * return values in AIDL.  
 */  
 @Override  
 public void basicTypes(int anInt, long aLong, boolean aBoolean,  
 float aFloat, double aDouble, java.lang.String aString)  
 throws android.os.RemoteException {  
 android.os.Parcel _data = android.os.Parcel.obtain();  
 android.os.Parcel _reply = android.os.Parcel.obtain();  
 try {  
 _data.writeInterfaceToken(DESCRIPTOR);  
 _data.writeInt(anInt);  
 _data.writeLong(aLong);  
 _data.writeInt(((aBoolean) ? (1) : (0)));  
 _data.writeFloat(aFloat);  
 _data.writeDouble(aDouble);  
 _data.writeString(aString);  
 mRemote.transact(Stub.TRANSACTION_basicTypes, _data,  
 _reply, 0);  
 _reply.readException();  
 } finally {  
 _reply.recycle();  
 _data.recycle();  
 }  
 }  
 }  
 static final int TRANSACTION_getPid = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);  
 static final int TRANSACTION_basicTypes = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);  
 }  
 /** Request the process ID of this service, to do evil things with it. */  
 public int getPid() throws android.os.RemoteException;  
 /**  
 * Demonstrates some basic types that you can use as parameters and return  
 * values in AIDL.  
 */  
 public void basicTypes(int anInt, long aLong, boolean aBoolean,  
 float aFloat, double aDouble, java.lang.String aString)  
 throws android.os.RemoteException;  
 }  

Step 2) Implement IRemoteService.aidl inside your service. So first create one service class name AidlService.java here

 import android.app.Service;  
 import android.content.Intent;  
 import android.os.IBinder;  
 import android.os.RemoteException;  
 public class AidlService extends Service {  
 @Override  
 public void onCreate() {  
 super.onCreate();  
 }  
 @Override  
 public IBinder onBind(Intent arg0) {  
 return mBinder.asBinder();  
 }  
 private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {  
 @Override  
 public int getPid() throws RemoteException {  
 return 0;  
 }  
 @Override  
 public void basicTypes(int anInt, long aLong, boolean aBoolean,  
 float aFloat, double aDouble, String aString)  
 throws RemoteException {  
 }  
 };  
 }  

Step 3) ServiceConnection class allow to create connection between IRemoteService and your service class. So bind your service inside your activity. Change your main activity code to as follows

 import android.app.Activity;  
 import android.content.ComponentName;  
 import android.content.Context;  
 import android.content.Intent;  
 import android.content.ServiceConnection;  
 import android.os.Bundle;  
 import android.os.IBinder;  
 public class BindAidlActivity extends Activity {  
 @Override  
 protected void onCreate(Bundle savedInstanceState) {  
 super.onCreate(savedInstanceState);  
 bindService();  
 }  
 public void bindService() {  
 Intent intent = new Intent(this, AidlService.class);  
 bindService(intent, new ConnectService(), Context.BIND_AUTO_CREATE);  
 }  
 public void stoppingService() {  
 Intent intent = new Intent(this, AidlService.class);  
 stopService(intent);  
 }  
 IRemoteService uAidlService;  
 public class ConnectService implements ServiceConnection {  
 @Override  
 public void onServiceConnected(ComponentName name, IBinder service) {  
 uAidlService = IRemoteService.Stub.asInterface(service);  
 }  
 @Override  
 public void onServiceDisconnected(ComponentName name) {  
 /**  
 * Called when service disconnected  
 */  
 }  
 }  
 }  

Download All Service Binding Example

Android News and source code