Wednesday 29 January 2014

compare two sounds in android

Compare two sounds in Android 


Hi guys to i am going to share you code for comparing to sounds without using Google Voice.

There is very fine library which allows developers to extract audio features and operate audio data like reading, cutting and trimming easily from an inputstream. It also provides tools for digital signal processing, renders the wavform or spectrogram for research and development purpose.

https://code.google.com/p/musicg/

and here is code to compare wave two sounds 

// create a wave objectWave wave = new Wave(path1);Wave wave1 = new Wave(path2);FingerprintSimilarity fingerprintSimilarity = wave .getFingerprintSimilarity(wave1);float score = fingerprintSimilarity.getScore();float similarity = fingerprintSimilarity.getSimilarity();Log.d("Similarsound", "Score : " + score + "\n Similarity : "+ similarity);




Tuesday 28 January 2014

Override Hardware buttons android


Hi guys Today i am going to share a piece of code for blocking hardware buttons and wake screen lock etc.( some code is deprecated for new android API )



Here is self explanatory example
 download 

Sunday 12 January 2014

Android Different Screen Sizes Support


Android Different Screen Sizes Support


Android powers hundreds of device types with several different screen sizes, ranging from small phones to large TV sets. Therefore, it’s important that you design your application to be compatible with all screen sizes so it’s available to as many users as possible.
But being compatible with different device types is not enough. Each screen size offers different possibilities and challenges for user interaction, so in order to truly satisfy and impress your users, your application must go beyond merely supporting multiple screens: it must optimize the user experience for each screen configuration.

  • Explicitly declare in the manifest which screen sizes your application supports

    By declaring which screen sizes your application supports, you can ensure that only devices with the screens you support can download your application. Declaring support for different screen sizes can also affect how the system draws your application on larger screens—specifically, whether your application runs in screen compatibility mode.
    To declare the screen sizes your application supports, you should include the <supports-screens> element in your manifest file.

Add following code in .manifest file:
<supports-screens                                 
    android:smallScreens="true"                    
    android:normalScreens="true"         
    android:largeScreens="true"            
    android:xlargeScreens="true"             
    android:anyDensity="true" />

  • Provide different layouts for different screen sizes

    By default, Android resizes your application layout to fit the current device screen. In most cases, this works fine. In other cases, your UI might not look as good and might need adjustments for different screen sizes. For example, on a larger screen, you might want to adjust the position and size of some elements to take advantage of the additional screen space, or on a smaller screen, you might need to adjust sizes so that everything can fit on the screen.
    The configuration qualifiers you can use to provide size-specific resources are smallnormallarge, and xlarge. For example, layouts for an extra large screen should go in layout-xlarge/.
    Beginning with Android 3.2 (API level 13), the above size groups are deprecated and you should instead use thesw<N>dp configuration qualifier to define the smallest available width required by your layout resources. For example, if your multi-pane tablet layout requires at least 600dp of screen width, you should place it in layout-sw600dp/. Using the new techniques for declaring layout resources is discussed further in the section about Declaring Tablet Layouts for Android 3.2.

You need to create different layout for diff screen size. Support all screen you need to create following layout:
  1. Low density Small screens QVGA 240x320 (120dpi):
    layout-small-ldpi (240x320)  
    layout-small-land-ldpi (320x240)
  2. Low density Normal screens WVGA400 240x400 (x432) (120dpi):
    layout-ldpi  (240 x 400 )
    layout-land-ldpi  (400 x 240 )
  3. Medium density Normal screens HVGA 320x480 (160dpi):
    layout-mdpi (320 x 480 )
    layout-land-mdpi (480 x 320 )
  4. Medium density Large screens HVGA 320x480 (160dpi):
    layout-large-mdpi (320 x 480 )
    layout-large-land-mdpi (480 x 320)
  5. Galaxy Tab ( 240 dpi ):
    layout-large  (600 x 1024) 
    layout-large-land  (1024 x 600)
  6. High density Normal screens WVGA800 480x800 (x854) (240 dpi):
    layout-hdpi (480 x 800)
    layout-land-hdpi (800 x 480)
  7. Xoom (medium density large but 1280x800 res) (160 dpi):
    layout-xlarge (800 x 1280)
    layout-xlarge-land (1280 x 800)

  • Provide different bitmap drawables for different screen densities

    By default, Android scales your bitmap drawables (.png.jpg, and .gif files) and Nine-Patch drawables (.9.pngfiles) so that they render at the appropriate physical size on each device. For example, if your application provides bitmap drawables only for the baseline, medium screen density (mdpi), then the system scales them up when on a high-density screen, and scales them down when on a low-density screen. This scaling can cause artifacts in the bitmaps. To ensure your bitmaps look their best, you should include alternative versions at different resolutions for different screen densities.
    The configuration qualifiers you can use for density-specific resources are ldpi (low), mdpi (medium), hdpi (high), andxhdpi (extra high). For example, bitmaps for high-density screens should go in drawable-hdpi/.
The size and density configuration qualifiers correspond to the generalized sizes and densities described in Range of screens supported, above.
Note: If you're not familiar with configuration qualifiers and how the system uses them to apply alternative resources, read Providing Alternative Resources for more information.
At runtime, the system ensures the best possible display on the current screen with the following procedure for any given resource:
  1. The system uses the appropriate alternative resource Based on the size and density of the current screen, the system uses any size- and density-specific resource provided in your application. For example, if the device has a high-density screen and the application requests a drawable resource, the system looks for a drawable resource directory that best matches the device configuration. Depending on the other alternative resources available, a resource directory with the hdpi qualifier (such as drawable-hdpi/) might be the best match, so the system uses the drawable resource from this directory.
  2. If no matching resource is available, the system uses the default resource and scales it up or down as needed to match the current screen size and density The "default" resources are those that are not tagged with a configuration qualifier. For example, the resources in drawable/ are the default drawable resources. The system assumes that default resources are designed for the baseline screen size and density, which is a normal screen size and a medium density. As such, the system scales default density resources up for high-density screens and down for low-density screens, as appropriate.

Screen characteristicQualifier        Description
SizesmallResources for small size screens.
normalResources for normal size screens. (This is the baseline size.)
largeResources for large size screens.
xlargeResources for extra large size screens.
DensityldpiResources for low-density (ldpi) screens (~120dpi).
mdpiResources for medium-density (mdpi) screens (~160dpi). (This is the baseline density.)
hdpiResources for high-density (hdpi) screens (~240dpi).
xhdpiResources for extra high-density (xhdpi) screens (~320dpi).
nodpiResources for all densities. These are density-independent resources. The system does not scale resources tagged with this qualifier, regardless of the current screen's density.
tvdpiResources for screens somewhere between mdpi and hdpi; approximately 213dpi. This is not considered a "primary" density group. It is mostly intended for televisions and most apps shouldn't need it—providing mdpi and hdpi resources is sufficient for most apps and the system will scale them as appropriate. If you find it necessary to provide tvdpi resources, you should size them at a factor of 1.33*mdpi. For example, a 100px x 100px image for mdpi screens should be 133px x 133px for tvdpi.
OrientationlandResources for screens in the landscape orientation (wide aspect ratio).
portResources for screens in the portrait orientation (tall aspect ratio).
Aspect ratiolongResources for screens that have a significantly taller or wider aspect ratio (when in portrait or landscape orientation, respectively) than the baseline screen configuration.
notlongResources for use screens that have an aspect ratio that is similar to the baseline screen configuration.



In addition to the traditional supports-screens parameters refer to the new Size Qualifiers launched in 3.2
The different resource configurations that you can specify based on the space available for your layout are summarized in table 2. These new qualifiers offer you more control over the specific screen sizes your application supports, compared to the traditional screen size groups (small, normal, large, and xlarge).
To help you target some of your designs for different types of devices, here are some numbers for typical screen widths

Using the size qualifiers from table 2, your application can switch between your different layout resources for handsets and tablets using any number you want for width and/or height. Here is an example from my own project where we were targets smallest device to large 10 inch tablets.
here is the screen Shoot of my own project structure.








 res/layout-small/main_activity.xml     # All small Screen less than 240x320

 res/layout-sw320dp/main_activity.xml   # a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc)

 res/layout-sw480dp/main_activity.xml   # a tweener tablet like the Streak (480x800 mdpi).

 res/layout-sw600dp/main_activity.xml   # a 7” tablet like Nuxes 7 etc (600x1024 mdpi) .

 res/layout-sw720dp/main_activity.xml   # a 10” tablet like Nuxes  10, Galaxy Tab 10 etc 
(720x1280 mdpi, 800x1280 mdpi, etc).


Hope this tutorial will help you for multiple screen supports.
Happpppy Coddddding :)



Tuesday 7 January 2014

How to scan for WiFi networks

How to scan for WiFi networks



Android allows applications to access to view the access the state of the wirless connections at very low level. Application can access almost all the information of a wifi connection.
The information that an application can access includes connected network's link speed,IP address, negotiation state, other networks information. Applications can also scan, add, save, terminate and initiate Wi-Fi connections.
Android provides WifiManager API to manage all aspects of WIFI connectivity. We can instantiate this class by callinggetSystemService method. Its syntax is given below:
WifiManager mainWifiObj;
mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE); 
In order to scan a list of wireless networks, you also need to register your BroadcastReceiver. It can be registered using registerReceiver method with argument of your reciever class object. Its sytanx is given below:
class WifiScanReceiver extends BroadcastReceiver {
   public void onReceive(Context c, Intent intent) {
   }
}
WifiScanReceiver wifiReciever = new WifiScanReceiver();
registerReceiver(wifiReciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));  
The wifi scan can be start by calling the startScan method of the WifiManager class. This method returns a list of ScanResult objects. You can access any object by calling the get method of list. Its syntax is given below:
List<ScanResult> wifiScanList = mainWifiObj.getScanResults();
String data = wifiScanList.get(0).toString();
Apart from just Scanning , you can have more control over your WIFI by using the methods defined in WifiManager class. They are listed as follows:
Sr.NoMethod & Description
1addNetwork(WifiConfiguration config)
This method add a new network description to the set of configured networks.
2createWifiLock(String tag)
This method creates a new WifiLock.
3disconnect()
This method disassociate from the currently active access point.
4enableNetwork(int netId, boolean disableOthers)
This method allow a previously configured network to be associated with.
5getWifiState()
This method gets the Wi-Fi enabled state
6isWifiEnabled()
This method return whether Wi-Fi is enabled or disabled.
7setWifiEnabled(boolean enabled)
This method enable or disable Wi-Fi.
8updateNetwork(WifiConfiguration config)
This method update the network description of an existing configured network.

Here is an example demonstrating the use of WIFI. It creates a basic application that scans a list of wirless networks and populate them in a list view.

Here is an example demonstrating the use of WIFI. It creates a basic application that scans a list of wirless networks and populate them in a list view.



package com.example.wifiscandemo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener
{
WifiManager wifi;
ListView lv;
TextView textStatus;
Button buttonScan;
int size = 0;
List<ScanResult> results;

String ITEM_KEY = "key";
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
SimpleAdapter adapter;

/* Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

textStatus = (TextView) findViewById(R.id.textStatus);
buttonScan = (Button) findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(this);
lv = (ListView)findViewById(R.id.list);

wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled() == false)
{
Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
wifi.setWifiEnabled(true);
}
this.adapter = new SimpleAdapter(MainActivity.this, arraylist, R.layout.row, new String[] { ITEM_KEY }, new int[] { R.id.list_value });
lv.setAdapter(this.adapter);

registerReceiver(new BroadcastReceiver()
{
@Override
public void onReceive(Context c, Intent intent)
{
results = wifi.getScanResults();
size = results.size();
}
}, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
}

public void onClick(View view)
{
arraylist.clear();
wifi.startScan();

Toast.makeText(this, "Scanning...." + size, Toast.LENGTH_SHORT).show();
try
{
size = size - 1;
while (size >= 0)
{
HashMap<String, String> item = new HashMap<String, String>();
item.put(ITEM_KEY,"SSID: "+ results.get(size).SSID + "\n"+
"BSSID : "+ results.get(size).BSSID + "\n"+
"capabilities: "+ results.get(size).capabilities+"\n"+
"frequency : "+ results.get(size).frequency + "\n"+
"level : "+ results.get(size).level + "\n"
);

arraylist.add(item);
size--;
adapter.notifyDataSetChanged();
}
}
catch (Exception e)
{ }
}
}


in this example 

BSSID The address of the access point.
SSID The network name.
capabilities Describes the authentication, key management, and encryption schemes supported by the access point.
frequency The frequency in MHz of the channel over which the client is communicating with the access point.
level The detected signal level in dBm.
timestamp Time Synchronization Function (tsf) timestamp in microseconds when this result was last seen.


and dont forget to include permissions in manifest
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />



Happppppy Codddding :)

Friday 3 January 2014

Android WebView Complete Example Tutorial


The WebView class allows you to display web pages as a part of your activity layout. WebView becomes helpful  when your application frequently displays content from online resources.It simplifies task of performing a network request, parsing the data and rendering it in other Android layout. We can directly make HTTP request to an URL and load the returned HTML into WebView.



In this tutorial I am going to demonstrate usage  of WebView.



WebView in Layout :
<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/webview"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"/>

Loading Web Page in WebView :

WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://www.google.com");

Loading html file from your SDCard or Assets or RAW folder.
webView.loadUrl("file:///android_res/raw/test.html");//from raw folder
webView.loadUrl("file:///android_asset/test.html");//from asset folder

Loading html String content :

String html="<html><body>Hello <b>Android</b> Web View</body></html>";
webview.loadData(html, "text/html", "utf-8");


Setting Permission on AndroidManifest.xml :

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

Enabling JavaScript in WebView :
JavaScript is disabled in the webpages loaded in WebView by default.

WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);

Changing the UserAgent in WebView :
If your Web Application is to be used only in your Android application, then you can define a custom user agent string with setUserAgentString(), then query the custom user agent in your web page to verify that the client requesting your web page is actually your Android application.
webSettings.setUserAgentString("CUSTOM_UA");

Overriding Page Navigation so link open within your WebView :
When the user clicks a link from a web page in your WebView, the default web browser opens and loads the destination URL. However, you can override this behavior for your WebView, so links open within your WebView.
To achieve this you need to setWebViewClient to your WebView.

WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new MyWebViewClient());
Here MyWebViewClient class 

private class MyWebViewClient extends WebViewClient {
 @Override
 public boolean shouldOverrideUrlLoading(WebView view, String url) {
    return true;
}
}
The above class overrides all URL loading and loads them into your WebView.
We can add few codes such as following to make more interactive. Which overrides URL loading for specific host only.

private class MyWebViewClient extends WebViewClient {
 @Override
 public boolean shouldOverrideUrlLoading(WebView view, String url) {
   if (Uri.parse(url).getHost().equals("www.example.com")) {
     // do not override; let my WebView load the page
     return false;
   }
 return true;
 }
}

For more topics about WebView , don't forget to visit my posts: