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

Sunday, 18 May 2014

Android Developer Tools Tutorial

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

Android Developer Tools Tutorial
The android developer tools let you create interactive and powerful application for android platform. The tools can be generally categorized into two types.
  1. SDK tools
  2. Platform tools

SDK tools

SDK tools are generally platform independent and are required no matter which android platform you are working on. When you install the Android SDK into your system, these tools get automatically installed. The list of SDK tools has been given below:
Sr.NoTool & description
1android
This tool lets you manage AVDs, projects, and the installed components of the SDK
2ddms
This tool lets you debug Android applications
3Draw 9-Patch
This tool allows you to easily create a NinePatch graphic using a WYSIWYG editor
4emulator
This tools let you test your applications without using a physical device
5mksdcard
Helps you create a disk image (external sdcard storage) that you can use with the emulator
6proguard
Shrinks, optimizes, and obfuscates your code by removing unused code
7sqlite3
Lets you access the SQLite data files created and used by Android applications
8traceview
Provides a graphical viewer for execution logs saved by your application
We will discuss three important tools here that are android,ddms and sqlite3.

Android

Android is a development tool that lets you perform these tasks:
  1. Manage Android Virtual Devices (AVD)
  2. Create and update Android projects
  3. Update your sdk with new platform add-ons and documentation
android [global options] action [action options]

DDMS

DDMS stands for Dalvik debug monitor server, that provide many services on the device. The service could include message formation,call spoofing , capturing screenshot , exploring internal threads and file systems e.t.c

RUNNING DDMS

From eclipse click on Window , Open Perspective , Other ... DDMS . Or simple just look on the left most top corner and click on ddms.

HOW IT WORKS

In android ,each application runs in its own process and each process run in the virtual machine. Each VM exposes a unique port , that a debugger can attach to.
When DDMS starts, it connects to adb. When a device is connected, a VM monitoring service is created between adb and DDMS, which notifies DDMS when a VM on the device is started or terminated.

USING DDMS

You can use DDMS for many tasks. For example , here we are using it to make sms , make call , and capture screenshot.

MAKING SMS

In the DDMS, select the Emulator Control tab. In the emulator control tab , click on SMS and start typing the SMS and then the incoming number. It is shown in the picture below.
Android Developer Tools Tutorial
Now click on send button, and you will see an sms notification in the emulator window. It is shown below:
Android Developer Tools Tutorial

MAKING CALL

In the DDMS, select the Emulator Control tab. In the emulator control tab , click on voice and then start typing the incoming number. It is shown in the picture below:
Android Developer Tools Tutorial
Now click on the call button to make a call to your emulator. It is shown below:
Android Developer Tools Tutorial
Now click on hangup in the eclipse window to terminate the call.
The fake sms and call can be viewed from the notification by just dragging the notification window to the center using mouse. It is shown below:
Android Developer Tools Tutorial

CAPTURING SCREENSHOT

You can also capture screenshot of your emulator. For this look for the camera icon on the right side under Devices tab. Just point your mouse over it and select it.
As soon as you select it , it will start the screen capturing process and will capture whatever screen of the emulator currently active. It is shown below:
Android Developer Tools Tutorial
The ecclipse orientation can be changed using Ctrl + F11 key. Now you can save the image or rotate it and then select done to exit the screen capture dialog.

Sqlite3

Sqlite3 is a command line program which is used to manage the SQLite databases created by Android applications. The tool also allow us to execute the SQL statements on the fly.
There are two way through which you can use SQlite , either from remote shell or you can use locally.

USE SQLITE3 FROM A REMOTE SHELL.

Enter a remote shell by entering the following command:
adb [-d|-e|-s {}] shell
From a remote shell, start the sqlite3 tool by entering the following command:
sqlite3
Once you invoke sqlite3, you can issue sqlite3 commands in the shell. To exit and return to the adb remote shell, enter exit or press CTRL+D.

USING SQLITE3 DIRECTLY

Copy a database file from your device to your host machine.
adb pull 
Start the sqlite3 tool from the /tools directory, specifying the database file:
sqlite3 

Platform tools

The platform tools are customized to support the features of the latest android platform.
The platform tools are typically updated every time you install a new SDK platform. Each update of the platform tools is backward compatible with older platforms.
Some of the platform tools are listd below:
  1. Android Debug bridge (ADB)
  2. Android Interface definition language (AIDL)
  3. aapt, dexdump , and dex e.t.c

Posted By MIrza Abdul Hannan12:37:00 pm

Android Data Backup Tutorial

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

Android Data Backup Tutorial

Android allows you to backup your application data to remote "cloud" storage, in order to provide a restore point for the application data and settings. You can only backup your application data. In order to access the other applications data, you need to root your phone.
In order to make a data backup application, you need to register your application with google backup service. This has been explained in the example. After registering , you have to specify its key in the AndroidManifest.XML
<application
   android:allowBackup="true"
   android:backupAgent="MyBackupPlace">

   <meta-data 
      android:name="com.google.android.backup.api_key"
      android:value="AEdPqrEAAAAIErlxFByGgNz2ywBeQb6TsmLpp5Ksh1PW-ZSexg" />
</application>
Android provides BackUpAgentHelper class to handle all the operations of data backup. In order to use this class , you have to extend your class with it. Its syntax is given below:
public class MyBackUpPlace extends BackupAgentHelper {

}
The persistent data that you want to backup is in either of the two forms. Either it could be SharedPrefrences or it could be File. Android supports both types of backup in the respective classes of SharedPreferencesBackupHelper and FileBackupHelper.
In order to use SharedPerefernceBackupHelper, you need to instantiate its object with the name of your sharedPerefernces File. Its syntax is given below:
static final String File_Name_Of_Prefrences = "myPrefrences";
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, File_Name_Of_Prefrences);
The last thing you need to do is to call addHelper method by specifying the backup key string , and the helper object. Its syntax is given below:
addHelper(PREFS_BACKUP_KEY, helper);
The addHelper method will automatically add a helper to a given data subset to the agent's configuration.
Apart from these methods, there are other methods defined in the BackupAgentHelper class. They are defined below:
Sr.NoMethod & description
1onBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState)
Run the backup process on each of the configured handlers
2onRestore(BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState)
Run the restore process on each of the configured handlers
The methods of the SharedPreferencesBackUpHelper class are listed below.
Sr.NoMethod & description
1performBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState)
Backs up the configured SharedPreferences groups
2restoreEntity(BackupDataInputStream data)
Restores one entity from the restore data stream to its proper shared preferences file store

Example

The following example demonstrates the use of BackupAgentHelper class to create backup of your application data.
To experiment with this example , you need to run this on an actual device or in an emulator.
StepsDescription
1You will use Eclipse IDE to create an Android application and name it as Backup under a package com.example.backup. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Register your application with Google backup service.
3Modify the AndroidManifest to add respective necessary key and other compoenets
4Create backup agent class with the name you specify at AndroidManifest.XML
5Run the application and verify the results
Register you android application with google backup service. In order to do that , visit this link. You must agree to the terms of service, and then enter the application package name. It is shown below:
Android Data Backup Tutorial
Then click on Register with android backup service. It would give you your key, along with your AndroidManifest code to copy. Just copy the key. It is shown below:
Android Data Backup Tutorial
Once you copy the key , you need to write it in your AndroidManifest.XML file. Its code is given below:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.backup"
   android:versionCode="1"
   android:versionName="1.0" >

   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="17" />

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:backupAgent="MyBackUpPlace"
      android:theme="@style/AppTheme" >
      <activity
         android:name="com.example.backup.MainActivity"
         android:label="@string/app_name" >
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
      <meta-data 
         android:name="com.google.android.backup.api_key"
         android:value="AEdPqrEAAAAIErlxFByGgNz2ywBeQb6TsmLpp5Ksh1PW-ZSexg" />

   </application>

</manifest>
Here is the code of BackUpAgentHelper class. The name of the class should be the same as you specified in the backupAgent tag under application in AndroidManifest.XML
package com.example.backup;

import android.app.backup.BackupAgentHelper;
import android.app.backup.SharedPreferencesBackupHelper;

public class MyBackUpPlace extends BackupAgentHelper {


   static final String File_Name_Of_Prefrences = "myPrefrences";
   static final String PREFS_BACKUP_KEY = "backup";

   @Override
   public void onCreate() {
      SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, 
      File_Name_Of_Prefrences);
      addHelper(PREFS_BACKUP_KEY, helper);
}

}

Test your BackupAgent

Once you've implemented your backup agent, you can test the backup and restore functionality with the following procedure, using bmgr.

INSTALL YOUR APPLICATION ON A SUITABLE ANDROID SYSTEM IMAGE.

If using the emulator, create and use an AVD with Android 2.2 (API Level 8).
If using a device, the device must be running Android 2.2 or greater and have Google Play built in.

ENSURE DATA BACKUP IS ENABLED

If using the emulator, you can enable backup with the following command from your SDK tools/ path:
adb shell bmgr enable true
If using a device, open the system Settings, select Privacy, then enable Back up my data and Automatic restore.

PERFORMING BACKUP

For testing purposes, you can also make a request with the following bmgr command:
adb shell bmgr backup your.package.name
Initiate a backup operation by typing the following command.
adb shell bmgr run
This forces the Backup Manager to perform all backup requests that are in its queue.

UNINSTALL AND REINSTALL YOUR APPLICATION

Uninstall the application with the following command:
adb uninstall your.package.name
Then reinstall the application and verify the results.

Posted By MIrza Abdul Hannan12:14:00 pm

Android Custom Fonts Tutorial

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

Android Custom Fonts Tutorial
In android , you can define your own custom fonts for the strings in your application. You just need to download the required font from the internet, and then place it in assets/fonts folder.
After putting fonts in the assets folder under fonts folder, you can access it in your java code through Typeface class. First , get the reference of the text view in the code. Its syntax is given below:
TextView tx = (TextView)findViewById(R.id.textview1);
The next thing you need to do is to call static method of Typeface class createFromAsset() to get your custom font from assets. Its syntax is given below:
Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/font name.ttf");
The last thing you need to do is to set this custom font object to your TextView Typeface property. You need to call setTypeface() method to do that. Its syntax is given below:
tx.setTypeface(custom_font);
Apart from these Methods, there are other methods de;fined in the Typeface class , that you can use to handle Fonts more effectively.
Sr.NoMethod & description
1create(String familyName, int style)
Create a Typeface object given a family name, and option style information
2create(Typeface family, int style)
Create a Typeface object that best matches the specified existing Typeface and the specified Style
3createFromFile(String path)
Create a new Typeface from the specified font file
4defaultFromStyle(int style)
Returns one of the default Typeface objects, based on the specified style
5getStyle()
Returns the Typeface's intrinsic style attributes

Example

Here is an example demonstrating the use of Typeface to handle CustomFont. It creates a basic application that displays a custom font that you specified in the fonts file.
To experiment with this example , you can run this on an actual device or in an emulator.
StepsDescription
1You will use Eclipse IDE to create an Android application and name it as CustomFonts under a package com.example.customfonts. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Download a font from internet and put it under assets/fonts folder.
3Modify src/MainActivity.java file to add necessary code.
4Modify the res/layout/activity_main to add respective XML components
5Modify the res/values/string.xml to add necessary string components
6Run the application and choose a running android device and install the application on it and verify the results
Following is the content of the modifed main activity filesrc/com.example.customfonts/MainActivity.java.
package com.example.customfonts;

import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      TextView tx = (TextView)findViewById(R.id.hello);
      Typeface custom_font = Typeface.createFromAsset(getAssets(),
      "fonts/Erika Type.ttf");
      tx.setTypeface(custom_font);
   }

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }
}
Following is the modified content of the xml res/layout/activity_main.xml.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical">

   <TextView
      android:id="@+id/hello"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:textSize="70dip"
      android:text="@string/hello_world" />

</LinearLayout>
Following is the content of the res/values/string.xml.
<?xml version="1.0" encoding="utf-8"?>
<resources>

   <string name="app_name">CustomFonts</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello</string>

</resources>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.customfonts"
   android:versionCode="1"
   android:versionName="1.0" >

   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="17" />

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      <activity
         android:name="com.example.customfonts.MainActivity"
         android:label="@string/app_name" >
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
    </application>
</manifest>
Let's try to run our Custom Font application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:
Anroid Loading Spinner Tutorial
As you can see that the text that appeared on the AVD has not a default android font, rather it has the custom font that you specified in the fonts folder.
Note: You need to take care of the size and the character supported by the font , when using custom fonts.

Posted By MIrza Abdul Hannan12:12:00 pm