Android Reverse Engineering - decompile .apk-.dex-.jar-.java

Reverse engineering of android java app using apktool, dex2jar, jd-gui to convert .apk file to .java.
By reverse engineering of android app (.apk file) we can get following :

NTC Nepal Telecom gprs setting via sms - free

Activating GPRS in NTC (for both prepaid and postpaid service) FREE

  1. Type vgprs (in your Message Box) & Send to 1400 for GPRS Activation. :) 

To get GPRS configuration for your mobile set : FREE

  1. Send SMS to 1404 - you need to enter following different code according to your mobile set and send it to 1404
    • Type gprs (nokia, lg, motorolla, indian etc) (in your Msg Box)
    • Type sagprs (samsung mobiles) (in your Message Box) 
    • Type segprs (sony ericsson mobiles)
    • Type chgprs (chinese mobiles)
  2. After few minutes you will get setting and save it using pin code 1234.
  3. You might need to restart your set. Enjoy Browsing !!!

Java- extract / unzip a zip file - working code example

How to Extract / unzip a zip file in Java - complete source code example .
import java.io.*;
import java.util.zip.*;

public class UnzipTest {
    public static void unzipFile(File f) throws ZipException, IOException {

        ZipInputStream zin = new ZipInputStream(new FileInputStream(f));
        System.out.println(f.getAbsoluteFile());

        String workingDir = f.getPath() + File.separator + "unziped";

        byte buffer[] = new byte[4096];
        int bytesRead;

Java: using recursion to read a folder and its content in tree format sub-folders/files in tree format

Java CODE: Using recursion to read a folder and its content - sub-folders/files in tree format.

public class TreeTest {
      public static void main(String[] args) {
            showDir(1, new File("D:\\test"));
      }

      static void showDir(int indent, File file) {
            for (int i = 0; i < indent; i++)
                  System.out.print(' ');
            System.out.println(file.getName());
            if (file.isDirectory()) {
                  File[] files = file.listFiles();
                  for (int i = 0; i < files.length; i++)
                        showDir(indent + 4, files[i]);
            }
      }
}

Java : Generate JTree from XML dynamically - code example

In this post, i am going to describe how to generate JTree in swing according to an XML document dynamically.


Used XML File : catalog.xml

Java : Html form parser return map of (name,value) pair of input attribute


Simple HTML Form Parser which parses the given string of HTML and returns Map of  (name,value) pair of form's input attribute.


CODE : MyHtmlFormParser class

Java : Counting frequency of word in a string using Map

Use a Map to map Map<String,Integer> the words with frequency.

String SPACE =" ";
String [] words = input.split(SPACE);
Map<String,Integer> frequency = new HashMap<String,Integer>();
for (String word:words){
    Integer f = frequency.get(word);
    frequency.put(word,f+1);
}

Then you can find out for a particular word with:
frequency.get(word);

Java: ping an URL from java application - code example

The code to ping a URL from java application is as follows :


public static void pingUrl(final String address) {
try {
final URL url = new URL("http://" + address);
final HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setConnectTimeout(1000 * 10); // mTimeout is in seconds
urlConn.connect();
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
System.out.println("Ping to "+address +" was success");
}
} catch (final IOException e) {
e.printStackTrace();
}
}
 


With response time:

public static void pingUrlWithResponseTime(final String address) {
try {
final URL url = new URL("http://" + address);
final HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setConnectTimeout(1000 * 10); // mTimeout is in seconds
final long startTime = System.currentTimeMillis();
urlConn.connect();
final long endTime = System.currentTimeMillis();
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
System.out.println("Time (ms) : " + (endTime - startTime));
System.out.println("Ping to "+address +" was success");
}
} catch (final IOException e) {
e.printStackTrace();
}
}

Android: Killing a running process with processid(pid) and package name

After analysis of source code of Android's package manager application, i found forceStopPackage method is used by system image to kill the processes- which uses android.Manifest.permission.FORCE_STOP_PACKAGES permission.  But problem is that this permission is granted only for system level application.

Android: Code for detecting if specific application or service running

For checking a application is running or not :
public static boolean isThisApplicationRunning(final Context context, final String appPackage) {
 if (appPackage == null) {
  return false;
 }
 final ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
 final List<RunningAppProcessInfo> runningAppProcesses = manager.getRunningAppProcesses();
 for (final RunningAppProcessInfo app : runningAppProcesses) {
  if (appPackage.equals(app.processName)) {
   return true;
  }
 }
 return false;
}



For checking a service is running or not :
public static boolean isThisServiceRunning( final Context context, final String servicePackageName) {
 final ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
 for (final RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
  if (servicePackageName.equals(service.service.getClassName())) {
   return true;
  }
 }
 return false;
}



Required Permission :
 <uses-permission android:name="android.permission.GET_TASKS" />

Android code for reading phone contacts detail

Here is code for reading all phone contacts(phone number,  email etc with their type) stored in android phone programmatically.

Android Reading Call Log from Phone Programmatically

Here is the code to read all call log data (MISSED, OUTGOING, INCOMING) from android phone programmatically.

Permission in AndroidManifest.xml:
Add the READ_CONTACTS permission to your AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_CONTACTS" />

Code :

Calling JavaScript Function from Android and Handling Result

In this tutorial I am going to describe JavaScriptInterface  for Calling Android Function from JavaScript i.e., JavaScript Binding to Android.

Setting up WebView
First add JavaScriptInterface to webView as follows. Here "MyAndroid" will be used later to call functions in JavaScriptInterface later.

google adsense payment in nepal - western union quick cash

Google recommend  Electronic Fund Transfer (EFT)   as a faster and more reliable form of payment. But, EFT are currently only available to a limited number of countries. Which doesn't include Nepal. So we have the only good option : Western Union Quick Cash.

Receiving payments by Western Union Quick Cash:

Western Union Quick Cash is a payment method that allows you to receive your AdSense payments in cash using the worldwide Western Union money transfer service. Payments will be available for pick up at your local Western Union Agent the day after they are sent according to our normal payment schedule.
Your Western Union Quick Cash payment will be made in US dollars. Conversion rates will be calculated according to the rate used by the Western Union Agent on the day you pick up your payment.

Steps :

1) Setup Google Adsense payment to Western Union Quick Cash:


  1. Sign in to your account at www.google.com/adsense.
  2. Visit the Home tab and click Account settings in the left hand panel.
  3. Click 'edit payment method' under the 'Payment settings' header.
  4. Select the Western Union Quick Cash radio button.
  5. Click Continue.
  6. Click Save changes to save your payment type.

2) Picking up WU payment

In order to pick up your payment by Western Union Quick Cash, please complete the following steps:
  1. Find a Western Union Agent located in the country where your payments are sent.
  2. Call the Western Union Agent to confirm that they offer the Quick Cash service.
  3. Bring the following information with you:

    - a valid government-issued photo ID (Passport, Driver's license, National ID etc)
    - sender's information: To determine which sender's information you should bring to your WU branch, please check the 'details' link on the payment line of your Payments page.
    • Google Inc. 1600 Amphitheatre Parkway, Mountain View, California 94043, USA. Phone Number:  650-253-4000     
    - amount of your payment, which you can find on your Payment History page
    - your unique MTCN (Money Transfer Control Number) which you can find by clicking on the 'details' link next to the Payment Issued line on your Payment History page
Hurrahs ------- Lets have a party ... 

java find path of current executing jar

Best solution : 
String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
You can use your own class name instead of 'Test'

Android JavaScriptInterface tutorial and example for calling JavaScript function from Android

In this tutorial I am going to describe JavaScriptInterface  for calling JavaScript function from Android i.e., JavaScript Binding to Android.

I have written a blog post about : Calling JavaScript Function from Android and Handling Result

Setting up WebView
First add JavaScriptInterface to webView as follows. Here "MyAndroid" will be used later to call functions in JavaScriptInterface later.

Android WebView WebChromeClient example tutorial

WebChromeClient is used to handle a JavaScript events in Android App which are produced by WebView. The examples of such events are : 
  • onCloseWindow
  • onProgressChanged
  • onJsAlert
  • onJsConfirm
  • onJsPrompt
  • onJsTimeout

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.

XSLT : Using reusable XSL to generate HTML Form dynamically

In this article , am going to describe how to generate html form dynamically using reusable xsl file.


Problem Statement :

Suppose I have large number of xml files :  There is one condition that : there won't be any more nested tags . But the name of property tag will be different for each xmldata file.
First xml:

Xsl transform in Java working example (xml to html)

In order to display XML documents, it is necessary to have a mechanism to describe how the document should be displayed. One of these mechanisms is Cascading Style Sheets (CSS), but XSL (eXtensibleStylesheet Language) is the preferred style sheet language of XML.
XSL can be used to define how an XML file should be displayed by transforming the XML file into a format such as HTML, PDF, etc..

Java - Single instance of application - working source code example

Having a single instance of an application is crucial in most of the software. In this article, I am giving an example on how to implement single instance of  an Application.
How it works :
  1. New instance of application tries to connect to a specific ServerSocket (localhost, port#) to detect running applications. And a running application must have a ServerThread to detect possible run of new instance of the same application
  2. The main Logic in steps
    • Find existing server socket running on localhost
    • If found(another instance was already running) --> exit current instance of application
    • else --
      •  start a new Server thread to detect run of future applications
      •  and start the application
Complete source code :

Some useful Regular Expressions for Find/Replace in Eclipse IDE

Regular expressions is powerful tool mostly used in search, edit and manipulate text. A regular expression define a search pattern for strings. The abbreviation for regular expression is "regex".Regular expressions are used in several programming languages. But, unfortunately each language / program supports regex slightly different.

In this blog, I am going to explain the use of Regular Expression(regex) in Eclipse IDE. There are eleven examples in total.

Singly Linked list with all operations in C++

Linked list with all operations. Insert, Delete items at various position.

#include <iostream.h>
#include <conio.h>
//singly link list
class linklist
{

Dynamic Implementation of Queue in C++ using linked list

Dynamic Implementation of Queue in C++ using linked list

#include <iostream.h>
#include <conio.h>

class queue
{
    struct node
    {

Dynamic Implementation of Stack in C++

Dynamic Implementation of Stack in C++ using linked list

#include <iostream.h>
#include <conio.h>

class stack
{

Recursion : Tower of Hanoi in C++

Tower of Hanoi by recursion

#include <iostream>
using namespace std;
int main()
{

C++ implementation of Circular Queue

C++ implementation of Circular Queue

#include <iostream.h>
#include <conio.h>
#define size 10

class queue
{

C++ implementation of front end fix and rear end vary queue

C++ implementation of front end fix and rear end vary queue

#include <iostream.h>
#include <conio.h>
#define size 10

class queue
{

C++ implementation of front and rear end varying queue

C++ implementation of front and rear end varying queue

#include <iostream.h>
#include <conio.h>
#define size 10

class queue
{

C++ implementation of top varying stack

C++ implementation of top varying stack

#include <iostream.h>
#include <conio.h>
#define size 10
using namespace std;
class stack
{

C++ implementation of fixed top stack

C++ implementation of fixed top stack

#include<iostream.h>
#include<conio.h>
#definesize 10
class stack
{
    int tos;
    int item[size];
    int pos;

List of good references for Speech / Speaker Recognition Project

Here is list of good references , that we followed for our final project. These  are also included in reference section of final report. 
After we decided to do final project on joint speech and speaker recognition, we did a lot of research and downloaded almost 2 GB of articles, lecture notes and etc. But, these article(around 30 MB) were really useful to us.
All of them are available on Web for free. Just google it.


  1. Assignment 3: GMM Based Speaker Identification EN2300 Speech Signal Processing, [ www.kth.se/polopoly_fs/1.41342!assignment_03.pdf]
  2. Conrad Sanderson, Automatic Person Verification Using Speech and Face Information - A Dissertation Presented to The School of Microelectronic Engineering Faculty of Engineering and Information Technology, Griffith University, August 2002, [revised February 2003].
  3. Douglas A Reynolds and Richard C Rose, Robust text-independent speaker identification using Gaussian mixture speaker models. IEEE Transactions on Speech and Audio Processing, 3(1):72–83, 1995.
  4. G. Saha, Sandipan Chakroborty, Suman Senapati , A New Silence Removal and Endpoint Detection Algorithm for Speech and Speaker Recognition Applications, Department of Electronics and Electrical Communication Engineering, Indian Institute of Technology, Khragpur, Kharagpur, India.
  5. J P Campbell, Jr. Speaker recognition: A tutorial. Proc. IEEE, 85(9):1437–1462, 1997.
  6. K.R. Aida–Zade, C. Ardil and S.S. Rustamov, Investigation of Combined use of MFCC and LPC Features in Speech Recognition Systems, World Academy of Science, Engineering and Technology, 2006
  7. L. R. Rabiner, “A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition”, vol-77, no. 2, pp. 257-286, 1989.
  8. Lasse L Mølgaard, Kasper W Jørgensen, Speaker Recognition: Special Course; IMM-DTU; 2005
  9. Mohamed Faouzi  BenZeghibaa , Joint Speech and Speaker Recognition,IDIAP  Research  Report, 2005.
  10. Robin Teo Choon Guan @ Myo Thant, Majority Rule- Based Non-Intrusive User Authentication by Speech: Part 2 (Speaker Verification), Thesis, School of Science and Technology, Sim University,2009.
  11. Shi-Huang Chen and Yu-Ren Luo , Speaker Verification Using MFCC and Support Vector Machine, Proceedings of the International Multi Conference of Engineers and Computer Scientists 2009, vol – I, IMECS 2009.
  12. Tomi Kinnunen , Spectral Features for Automatic Text-Independent Speaker Recognition- Licentiate’s Thesis, University of Joensuu, Department of Computer Science, Finland, 2003.
  13. Waleed H. Abdulla and Nikola K. Kasabov, The Concepts of Hidden Markov Model in Speech Recognition, Knowledge Engineering Lab, Department of Information Science, University of Otago,New Zealand, 1999.

save an Android application's state and restore

The savedInstanceState way for saving state associated with a current instance of an Activity, for example - current navigation, selections, unsaved text.. etc, so that if Android destroys and recreates an Activity, it can come back as it was before.

We should override onSaveInstanceState(Bundle savedInstanceState) and write the application state values you want to change to the Bundle parameter like this:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  // Save UI state changes to the savedInstanceState.
  // This bundle will be passed to onCreate if the process is
  // killed and restarted.
  savedInstanceState.putBoolean("MyBoolean", true);
  savedInstanceState.putDouble("myDouble", 1.9);
  savedInstanceState.putInt("MyInt", 1);
  savedInstanceState.putString("MyString", "Welcome back to Android");
  // etc.
  super.onSaveInstanceState(savedInstanceState);
}

This stores the values into  Bundle in a NVP ("Name-Value Pair") map, and it will get passed in to onCreate and also onRestoreInstanceState.

Extract the values stored:

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  // Restore UI state from the savedInstanceState.
  // This bundle has also been passed to onCreate.
  boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
  double myDouble = savedInstanceState.getDouble("myDouble");
  int myInt = savedInstanceState.getInt("MyInt");
  String myString = savedInstanceState.getString("MyString");
}

Silence Removal and End Point Detection JAVA Code

For the purpose of silence removal of captured sound, we used the algorithm  in our final year project. In this post, I am publishing the endpoint detection and silence removal code ( implementation of this algorithm in JAVA).

These links might be useful to you as well.
The constructor of following java class EndPointDetection takes two parameters
  1. array of original signal's amplitude data : float[] originalSignal
  2. sampling rate of original signal in Hz : int samplingRate
The Java Code :
package org.ioe.tprsa.audio.preProcessings;

declare global variable in android- example code

To declare global variable in android, you need to 
1) create your own subclass of android.app.Application
2) and then specify that class in the application tag in your manifest. 
Android will automatically create an instance of that class and make it available for your entire application. You can access it from any context using the Context.getApplicationContext() method (Activity also provides a method getApplication() which has the exact same effect):
  • Sub Class of Application :
     public class MyApp extends Application {
           String foo;
      }
  • In the AndroidManifest.xml add android:name
 <application 
     android:icon="@drawable/icon" 
     android:label="@string/app_name" 
     android:name="com.company.MyApp">
  </application>

Full Example :

What's the difference between a primary key and a unique key?

Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where unique creates a non-clustered index by default. Another major difference is that, primary key does not allow NULLs, but unique key allows one NULL only.

What is de-normalization and when would you go for it?

As the name indicates, de-normalization is the reverse process of normalization. It is the controlled introduction of redundancy in to the database design. It helps improve the query performance as the number of joins could be reduced.

What are clustered index and non clustered index


With a clustered index the rows are stored physically on the disk in the same order as the index. There can therefore be only one clustered index.
With a non clustered index there is a second list that has pointers to the physical rows. You can have many non clustered indexes, although each new index will increase the time it takes to write new records.
It is generally faster to read from a clustered index if you want to get back all the columns. You do not have to go first to the index and then to the table.
Writing to a table with a clustered index can be slower, if there is a need to rearrange the data.
In other words,
A clustered index means you are telling the database to store close values actually close to one another on the disk. This has the benefit of rapid scan / retrieval of records falling into some range of clustered index values.


From Wikipedia :
database index is a data structure that improves the speed of data retrieval operations on a database table at the cost of slower writes and increased storage space

Silence Removal and End Point Detection MATLAB Code

Visit http://ganeshtiwaridotcomdotnp.blogspot.com/2011/06/final-report-text-prompted-remote.html for more detail about our project.
For the purpose of silence removal of captured sound, we used the algorithm specified in
"A New Silence Removal and Endpoint Detection Algorithm for Speech and Speaker Recognition Applications"
Our actual system was in JAVA but we verified the performance of this algorithm in MATLAB.

Inputs and Output
Before silence removal
After automatic silence removal
Here is the Matlab code : 
It first records sound for 5 seconds and removes the silence and then plays back.