Search Wikipedia

Search results

Jun 25, 2015

How to Send Email

We  do not need to develop our email client from scratch because they are already available like Gmail and K9mail. But we will need to send email from our android application, where we will have to write an Activity that need to launch an email client and sends an email using our android device. For this purpose, our Acivity will send an ACTION_SEND along with appropriate data load, to the Android Intent Resolver. The specified chooser gives the proper interface for the user to pick how to send our email data.


STEP 1: INTENT OBJECT- Action to send Email


We will use ACTION_SEND action to launch an email client intalled on our Android device.
Following is simple syntax to create an intent with ACTION_SEND action.
Intent emailIntent = new Intent(Intent.ACTION_SEND);

STEP 2: INTENT OBJECT- Data/Type to send Email


To send an email we need to specify mailto: as URI using setData() method and datatype will be tottext/plain using setType() method as follows:
emailItent.setData(Uri.parse("mailto:"));
emailIntent.settype.settype("text/plain");

STEP 3: INTENT OBJECT- Extra to send Email


Android has built-in support to add TO,SUBJECT,CC,TEXT etc. fields which can be attached to intent before sending the intent to target email client.
Here is an example showing how to assign extra data to your intent:
emailIntent. putExtra(Intent.EXTRA_EMAIL,new String[]{"recipent@example.com"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT,"subject of email");
emailIntent.putExtra(Intent.EXTRA_TEXT,"body of email");

Jun 24, 2015

Create and Send Notifications

There is  a simple method  to create notification. Follow the following steps to create a notification.

STEP 1 - CREATE NOTIFICATION BUILDER

As a first step is to create a notification builder using NotificationCompat.Builder.build(). We will use Notification to set various Notification properties like its small and large icons,title,priority etc.
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)

STEP 2 - SETTING NOTIFICATION PROPERTIES

Once we have Builder object, we can set its Notification properties using Builder object as per our requirement. But this is mandatory to set atleast following:
  • A small icon, set by setSmallIcon()
  • A title, set by setContentTitle()
  • Detail text, set by setContentText()
mBuilder.setSmallIcon(R.drawable.notification_icon);
mBuiler.setContentTitle("Notification Alert, Click Me !");
mBuilder.setContentText("Hi, This is Android Notification Detail");

STEP 3 - ATTACH ACTIONS

This is an optional part and required if we want to attach an action with the application. An action allows users to go directly from the notification to an Activity in our application, where user can look at one or more events or do further work.

The action is defined by a PendingIntent containing an Intent that starts an Activity in our application. To asscociate the PendingIntent with a gesture, call the appropriate method of NotificationBuilder.Builder. For example, if we want to start Activity when user clicks the notification text in the notification drawer, you add the PendingIntent by calling setContentIntent().

A PendingIntent object helps us to perform an action on our application's behalf, often at a later time, without caring of whether or  not our application is running.

We can help of stack builder object which will contain an artificial back stack for the started Activity. This ensure the navigating backward from the Activity leads out of our application to the Home screen.

Intent resultIntent = new Intent(this,ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ResultActivity.class);
//Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mbuilder.setCotentIntent(resultPendingIntent);

STEP 4 - ISSUE THE NOTIFICATION

Finally, we can pass the Notification object to the system by calling NotificationManager.notifiy() to send our notification. Make sure we call NotificationCompat.Builder.build() method on builder object before notifying it. This method combines all of the options that have been set and return a new Notification object.

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//notificatioID allows us to update the notification later on 
mNotificationManager.notify(notificationID, mBuilder.build());

May 6, 2014

Adjust Screen Brightness in Android with example

Screen Brightness in Android can be controlled programmatically in simple way. This tutorial explains the process with an example. Native brightness control in Android device has a Seekbar that adjust the screen brightness. The below tutorial has UI in a similar way.You take a look at SeekBar tutorial here if needed. 

android.provider.Settings.System - This class contains miscellaneous system preferences. There are convenience functions for accessing individual system settings. android.provider.

Settings.System.getInt - Convenience function for retrieving a single system settings value as an integer. Note that internally setting values are always stored as strings; this function converts the string to an integer for you. The default value will be returned if the setting is not defined or not an integer. 

android.provider.Settings.System.SCREEN_BRIGHTNESS - String that holds Screen Brightness value ranging from 0 to 255.

May 4, 2014

Drawing with Canvas in Android

Before starting this tutorial please check this site https://developer.mozilla.org/enUS/docs/Web/HTML/Canvas/Drawing_graphics_with_canvas and see that you must use paths (2nd example, beginPath) rather than drawing point by point.

On your Activity
private ArrayList _graphics = new ArrayList();
private Paint mPaint;
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(new DrawingPanel(this));
  mPaint = new Paint();
  mPaint.setDither(true);
  mPaint.setColor(0xFFFFFF00);
  mPaint.setStyle(Paint.Style.STROKE);
  mPaint.setStrokeJoin(Paint.Join.ROUND);
  mPaint.setStrokeCap(Paint.Cap.ROUND);
  mPaint.setStrokeWidth(3);
  }
On your SurfaceView
@Override
public boolean onTouchEvent(MotionEvent event) {
  synchronized (_thread.getSurfaceHolder()) {
    if(event.getAction() == MotionEvent.ACTION_DOWN){
      path = new Path();
      path.moveTo(event.getX(), event.getY());
      path.lineTo(event.getX(), event.getY());
    }else if(event.getAction() == MotionEvent.ACTION_MOVE){
      path.lineTo(event.getX(), event.getY());
    }else if(event.getAction() == MotionEvent.ACTION_UP){
      path.lineTo(event.getX(), event.getY());
      _graphics.add(path);
    }
    return true;
  }
}
@Override
public void onDraw(Canvas canvas) {
  for (Path path : _graphics) {
    //canvas.drawPoint(graphic.x, graphic.y, mPaint);
    canvas.drawPath(path, mPaint);
  }
}

Explanation

We create a path and start that path when the MotionEvent is down, or when the user first touch the screen, then add a lineTo, the x and y when the user moves his fingers.

Then stop and push the path we had build to our array of Paths.
 public boolean onTouchEvent(MotionEvent event) { .... }

 Then during the draw function we loop through the array and print them on our canvas.
 public void onDraw(Canvas canvas) { ... }

How to Generate random number in Android

Generating Random Number in Android

To generate random number in Android, class java.util.Random can be used.

This class java.util.Random provides methods that generates pseudo-random numbers of different types, such as int, long, double, and float.

It support two public constructor:
Random() - Construct a random generator with the current time of day in milliseconds as the initial state.
Random(long seed) - Construct a random generator with the given seed as the initial state.


A simple example of Alarm Service, using AlarmManager

Alarm Service in Android

AlarmManager class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future. When an alarm goes off, the Intent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running. 

In this exercise, a scheduled alarm of 10 seconds will start a service, MyAlarmService. 

Modify main.xml to have two button to start and cancel the alarm.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/startalarm"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start"
/>

<Button
android:id="@+id/cancelalarm"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Cancel"
/>

</LinearLayout>

ProgressBar running in AsyncTask

ProgressBar in Android

It's a exercise of a Horizontal ProgressBar which running in a background AsyncTask.

Modify main.xml to have a button to start the progress, and the ProgressBar.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 >
<TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="@string/hello"
 />
<Button
android:id="@+id/playvideoplayer"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="- PLAY Video -"
 />
<Button
android:id="@+id/pausevideoplayer"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="- PAUSE Video -"
 />
<SurfaceView
android:id="@+id/surfaceview"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 />
</LinearLayout>

May 2, 2014

AndroidSpeech: Android can speak!

A new feature, Text-To-Speech (TTS), have been introduced in version 1.6 of the Android platform. Also known as 'speech synthesis', TTS enables Android device to 'speak' text of different languages.

it's a very simple code to make Android speech. It can speech only.

Create a Android Application, with Target platform 1.6, API Level 4. Modify the code as following.

AndroidSpeech.java


package com.kais.AndroidSpeech;

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;

public class AndroidSpeech extends Activity implements OnInitListener{

TextToSpeech myTTS;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
  
     myTTS = new TextToSpeech(this, this);
 }

@Override
public void onInit(int status) {
// TODO Auto-generated method stub

String myText1 = "Hello Android!";
       String myText2 = "I can speech.";
       myTTS.speak(myText1, TextToSpeech.QUEUE_FLUSH, null);
       myTTS.speak(myText2, TextToSpeech.QUEUE_ADD, null);
}

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
myTTS.shutdown();
}
}

For more details of Android Text-To-Speech, refer to:
Android Developers Blog: An introduction to Text-To-Speech in Android: "We've introduced a new feature in version 1.6 of the Android platform: Text-To-Speech (TTS). Also known as 'speech synthesis', TTS enables your Android device to 'speak' text of different languages."

Uses Tabs to navigate between different views, TabWidget

Using TabWidget in Android

A TabWidget offers the ability to easily draw an interface that uses tabs to navigate between different views.



Start a new Android Application, named AndrodTab extends TabActivity and modify the xml file as below.


May 1, 2014

Implement Android MP3 Player using MediaPlayer

MediaPlayer in Android

MediaPlayer class can be used to control playback of audio/video files and streams. It is a example to implement MP3 Player using MediaPlayer. Please note that you have to keep follow the State Diagram, otherwise IIlegalStateException will be thrown.


Create a new Android Project in Eclipse, using the auto-generated code extend from ActionBarActivity.
The mp3 file is stored in /res/raw/vespers.mp3. Filename match with the following code in initMediaPlayer().

Working With Android Contacts (Part 2)

Gluing together (API 2.0 and API 1.6 & Before)

To put this together into an application there are a few glue pieces that need to be setup along with creating classes to manage accessing the data. First we need to create a set of classes to hold the data. Also we'll create a class to handle 2.0 API calls and a class to handle 1.6 and earlier API calls. There's also a wrapper class that determines and loads the proper class.
Contact Data Classes
The contact classes are a series of classes to hold a list of contacts. The list is stored in the class ContactList that maintains an ArrayList of Contacts. The Contact objects are represented in the Contact class. The contact class stores all the data from the Android contact record. In addition to the ContactList and Contact classes there are specialized classes to represent some of the record data.
We will create classes to represent the address and email. Most of these classes are mere data storage classes with variables and getter/setters.

ContactList
The ContactList class is a very basic class designed to hold an ArrayList of instances of the Contact class below. We've left this class very plain and ready to be expanded to suit your needs. 

package com.kais.android.ContactAPI.objects;
import java.util.ArrayList;
 public class ContactList {
 private ArrayList<Contact> contacts = new ArrayList<Contact>();
 public ArrayList<Contact> getContacts() {
   return contacts;
  }
 public void setContacts(ArrayList<Contact> contacts) {
   this.contacts = contacts;
  }
  public void addContact(Contact contact) {
   this.contacts.add(contact);
  }
   public ContactList() {
   }
  }

Working With Android Contacts (Part 1)

Introduction To Android Contacts

Learn to work with the Android contacts database. Basic knowledge of accessing SQLite in Android along with using Cursors is expected. See the Android SQLite and Cursor Article for more information. Google changed the contacts database moving from 1.x to 2.0 versions of Android. This tutorial will be broken into 2 sections. First covering accessing contacts in Android 2.0 and  Android 1.6 & before. Third we'll glue it all together with a class that abstracts specific classes for each version and a set of classes to manage the data from the contact records for that tutorial click here.

API For 1.6 and Before

Granting Access
Before an application can query the contact records access must be granted through the AndroidManifest.xml file stored in the root of the project. Add the following uses-permission belows the uses-sdk statement. 
<uses-permission android:name="android.permission.READ_CONTACTS" />
Querying the contact database
Retrieving Contact Details
Basic contact information stored in Contacts table with detailed information stored in individual tables for normalization. In Android 1.x to query the base contact records the URI to query is stored in People.CONTENT_URI. 
package com.kais.TestContacts;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts;
import android.provider.Contacts.People;

public class TestContacts extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(People.CONTENT_URI, 
   null, null, null, null);
        if (cur.getCount() > 0) {
      while (cur.moveToNext()) {
          String id = cur.getString(cur.getColumnIndex(People._ID));
          String name = cur.getString(cur.getColumnIndex(People.DISPLAY_NAME));
      }
        }
    }
}
Start off with the standard view loading. Then we create a ContentResolver instance that will be used to query the SQLite database that stores the contacts. The ContentResolver query returns a Cursor instance that holds the contact records queried from the database. Then take the ID field from the contact record and store it in the string id and take the DISPLAY_NAME field and place it in the string name. For more information about cursors see the Android Cursor Tutorial.

Accessing Data with Android Cursors (Part 2)

Retrieving Data

Retrieving data from SQLite databases in Android is done using Cursors. The Android SQLite query method returns a Cursor object containing the results of the query. To use Cursors android.database.Cursor must be imported.

About Cursor

Cursors store query result records in rows and grant many methods to access and iterate through the records. Cursors should be closed when no longer used, and will be deactivated with a call to Cursor.deactivate() when the application pauses or exists. On resume the Cursor.requery() statement is executed to re-enable the Cursor with fresh data. These functions can be managed by the parent Activity by calling startManagingCursor(). 

package com.kais.TestingData;

import java.util.Locale;

import android.app.Activity;
import android.os.Bundle;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class TestingData extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        SQLiteDatabase db;
        
        db = openOrCreateDatabase(
         "TestingData.db"
         , SQLiteDatabase.CREATE_IF_NECESSARY
         , null
         );
        db.setVersion(1);
        db.setLocale(Locale.getDefault());
        db.setLockingEnabled(true);
        
        Cursor cur = db.query("tbl_countries", 
         null, null, null, null, null, null);
        
        cur.close();
    }
}

Open the database as before. The query performed will return all records from the table tbl_countries. Next we'll look at how to access the data returned.

Apr 30, 2014

Accessing Data with Android Cursors (Part 1)

Creating and connecting to a Database

Create a new project in Eclipse called TestingData. Import android.database.sqllite.SQLiteDatabase in this project.

package com.kais.testingdata;

import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//here we create a database called TestingData.db
SQLiteDatabase db;
db = openOrCreateDatabase("TestingData.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
}

Creating Tables

Tables are created by executing statements on the database. The queries should be executed with the execSQL statement.Use  the setVersion(), setLocale() and setLockingEnabled() methods to set these properties. These will be demonstrated in the creating tables example.
Just put these lines of codes below the creation of database.

final String CREATE_TABLE_COUNTRIES = "CREATE TABLE tbl_countries("+ "id INTEGER                                                                                     PRIMARY KEY AUTOINCREMENT,"+"country_name                                                                           TEXT);";

final String CREATE_TABLE_STATES = "CREATE_TABLE tbl_states("+" id INTEGER PRIMARY                                                                   KEY AUTOINCREMENT,"+" state_name TEXT "+"                                                                                 country_id INTEGER KEY NULL CONSTRAINT "+"                                                                               country_id INTEGER NOT NULL CONSRAINT "+"                                                                                  country_id REFRENCES tbl1_countries(id) "+" ON DELETE                                                                      CASCADE);";

db.execSQL(CREATE_TABLE_COUNTRIES);
db.execSQL(CREATE_TABLE_STATES);

final String CREATE_TRIGGER_STATES = 
        "CREATE TRIGGER fk_insert_state BEFORE "
        + "INSERT on tbl_states"
        + "FOR EACH ROW "
        + "BEGIN "
                                + "SELECT RAISE(ROLLBACK, 'insert on table
                               "+" tbl_states violates foreign key constraint 
                               "+" fk_insert_state') WHERE (SELECT id FROM "+" tbl_countries WHERE id =                                         NEW.country_id) IS NULL; "+" END;";

db.execSQL(CREATE_TRIGGER_STATES);


Additionally here we manually have to create triggers to handle the foreign key relationships between the table. In  a production application there would also need to be foreign key triggers to handle row updates and deletes. The foreign key triggers are executed with execSQL just like the table creation.

Inserting Records

Android comes with a series of classes that simplify database usage. Use a ContentValues instance to create a series of table field to data matchings that will be passed into an insert() method. Android has created similar methods for updating and deleting records. 

ContentValues values = new ContentValues();
        values.put("country_name", "US");
        long countryId = db.insert("tbl_countries", null, values);
        ContentValues stateValues = new ContentValues();
        stateValues.put("state_name", "Texas");
        stateValues.put("country_id", Long.toString(countryId));
        try {
            db.insertOrThrow("tbl_states", null, stateValues);
        } catch (Exception e) {
            //catch code
        }
Append this code to the previous example. First create a ContentValues object to store the data to insert and use the put method to load the data. Then use the insert() method to perform the insert query into SQLite. The insert() function expects three parameters, the table name, null, and the ContentValues pairs. Also a long is returned by the insert() function. This long will hold the primary key of the inserted row.

Mar 27, 2014

Using Google Maps V2 in Android

1. Downloading Google Play Services

Google made new Maps V2 API as a part of Google Play Services SDK. So before we start developing maps we need to download google play services from SDK manger. You can open SDK manager either from Eclipse or from android sdk folder.
Open Eclipse ⇒ Windows ⇒ Android SDK Manager and check whether you have already downloaded Google Play Services or not under Extras section. If not select play services and install the package.

Downloading Google Play Services

2.Importing Google Play Services in Eclipse

After downloading play services we need to import it to Eclipse which will be used as a library for our maps project.
1. In Eclipse goto File ⇒ Import ⇒ Android ⇒ Existing Android Code Into Workspace
2. Click on Browse and select Google Play Services project from your android sdk folder. You can locate play services library project from
android-sdk-windows\extras\google\google_play_services\libproject\google-play-services_lib
3. Importantly while importing check Copy projects into workspace option as shown in the below image.

Importing Google Play Services

Dec 17, 2013

Working with Camera in Android

Taking a Picture in Android


Create a new project in Eclipse from File ⇒ New ⇒ Android ⇒ Application Project and fill all the required information. I left my main activity as MainActivity.java

Working with camera needs set of permissions and features in the AndroidManifest.xml file. Add following in your AndroidManifest.xml

android.hardware.camera – Required to use camera hardware
Adding required permissions in manifest file

Dec 10, 2013

Custom Dialog in Android

Creating a Custom Dialog in Android

I create a new android application project called "Custon_dialog"
Then I need to create a custom layout for my custom dialog and for this I create a new xml file called "dialog.xml"
In my custom dialog i want to show a picture and  some texts.
So, i drag a picture in my drawable folder.

dialog.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="110dp"
        android:layout_height="160dp"
        android:contentDescription="@string/todo"
        android:padding="20dp"
        android:src="@drawable/android" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="170dp"
        android:layout_height="211dp"
        android:text="@string/i_love_android" 
        android:textSize="25sp"/>

</LinearLayout>

Android Custom ListView With Images And Text

Customizing of ListView 

Today I am gonna customize the listview with images and text.
For this I create a new project called "Listv"
Then I drag a listview in "activity_main" xml file.


This xml file code looks like this:

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

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >
    </ListView>
</RelativeLayout>

Dec 5, 2013

Customization of Gridview

Customizing the Gridview 


After completion of simple gridview, now I am going to customize that gridview like opening the full-sized images from gridview and naming the images of the gridview.

For this, i create a new android project called "Grid_cus"
As we have done before, drag the gridview layout in graphical layout as shown below:

Draging Gridview in the layout


As like before tutorial, place the pictures in res->drawable-hdpi folder.
Then  i create a new class called "ImageControl.java" and write these codes :

public class ImageControl extends BaseAdapter{
Context mcontext;

public  static int[] ImageIds= { R.drawable.a, R.drawable.a1,R.drawable.a2, R.drawable.a3,
R.drawable.f, R.drawable.e,R.drawable.a7, R.drawable.a6,R.drawable.a5, R.drawable.a4,R.drawable.r, R.drawable.a1,R.drawable.v};

String texts[] = new String[]{"good","best","bad","damn","lool","joker","hard",
"kool","magic","aaare","pop","rock"};

public ImageControl(Context context){
mcontext = context;
}

Dec 3, 2013

Basic GridView Layout in Android

Creating a Basic GridView Layout in android

 GridView is a viewGroup that displays items in a two-dimensional,scrollable grid. The grid items are automatically inserted to the layout using a ListAdapter.

Today i am gonna create a simple Gridview layout.Now  I prepare images which i want to show in grid layout and place them in res->drawable-hdpi folder.

Images in Drawable-hdpi which will be shown in Gridview

I go to activity_main.xml and drag gridview layout from Palette or I can also write code directly for gridview which will be like this:

activity_main.xml

}