Sunday, 30 October 2011

Android Notification Example

Here below example show notification and cancel notification.

First i created application with 2 buttons one is for show and other one is for cancel.
when user click one show button notification will be appear and when user click on
cancel button cancel the notification.

Android UI layout(main.xml)

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/show"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Show Notification" />

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

</LinearLayout>

Android Activity(MainActivity.java)

package com.androidsurya.notification;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
NotificationManager notificationManager;
Notification notificationObj;
PendingIntent pendingIntent;
String notificationTitle = "Notification Titile!";
String notificationText = "Notification text display";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button show = (Button) findViewById(R.id.show);
show.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),
MainActivity.class);
notificationManager = (NotificationManager)                    getSystemService(Context.NOTIFICATION_SERVICE);
notificationObj = new Notification(R.drawable.ic_launcher,
"Show Notification !", System.currentTimeMillis());

pendingIntent = PendingIntent.getActivity(MainActivity.this, 0,
intent, Intent.FLAG_ACTIVITY_NEW_TASK);
notificationObj.defaults |= Notification.DEFAULT_SOUND;
notificationObj.setLatestEventInfo(getApplicationContext(),
notificationTitle, notificationText, pendingIntent);
notificationManager.notify(0, notificationObj);

}
});
Button cancel = (Button) findViewById(R.id.cancel);
cancel.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
notificationManager.cancel(0);
}
});
}

@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;
}

}

Register Activity in Android Manifest file

 <activity
            android:name="com.androidsurya.notification.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>

Output Screenshot:






































Wednesday, 26 October 2011

How to Show Soft Keyboard Programatically in Android

Hi This below code is use full for show keyboard programatically when Activity start  or Dialog show.

Just copy this below code as per your requirement in Activity or with in Dialog

InputMethodManager imputMM=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imputMM.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);

Hide Soft Keyboard Programatically in Android

Hi This below code is use full for hide keyboard programatically when Activity start  or Dialog show.

Just copy this below code as per your requirement in Activity or with in Dialog

InputMethodManager imputMM  (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imputMM.hideSoftInputFromWindow(singleedittext.getWindowToken(),0); 

Tuesday, 25 October 2011

Android Face Detection Example

In Android Sdk provide rich class called android.media.FaceDetector to identify the faces of people in a Bitmap graphic object.
In this below example we can see using FaceDetector how i find any people faces in Bitmap image .

Here below class i am using FaceDetector i can apply one rectangle shape to face.

Here i am using one image(aishwarya.png) that can be converted into Bitmap image
and Apply FaceDetection view on Image.and set that image to Activity View.

Note: Dont forget to place (aishwarya.png) in drawable folder.you can use your own image insted of (aishwarya.png) no problem .but u should you should use (yourpngfilename.png) insted of (aishwarya.png) in the below code

Android Activity(FaceDetectorActivity.java)

package com.androidsurya.facemodule;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.os.Bundle;
import android.view.View;

public class FaceDetectorActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new faceView(this));
}

private class faceView extends View {
// numberOfFace is for how many faces you want to find
private int numberOfFace = 1;
private FaceDetector faceDectect;
private FaceDetector.Face[] faceObj;
float eyesDistance;
int numberOfFacesDetected;
Bitmap bitmapImag;

public faceView(Context context) {
super(context);
// TODO Auto-generated constructor stub

BitmapFactory.Options BitmapFactoryOptionsbfo = new BitmapFactory.Options();
BitmapFactoryOptionsbfo.inPreferredConfig = Bitmap.Config.RGB_565;
bitmapImag = BitmapFactory.decodeResource(getResources(),
R.drawable.aishwarya, BitmapFactoryOptionsbfo);
faceObj = new FaceDetector.Face[numberOfFace];
faceDectect = new FaceDetector(bitmapImag.getWidth(),
bitmapImag.getHeight(), numberOfFace);
numberOfFacesDetected = faceDectect.findFaces(bitmapImag, faceObj);

}

@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub

canvas.drawBitmap(bitmapImag, 0, 0, null);

Paint myPaint = new Paint();
myPaint.setColor(Color.YELLOW);
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setStrokeWidth(2);

for (int i = 0; i < numberOfFacesDetected; i++) {
Face face = faceObj[i];
PointF myMidPoint = new PointF();
face.getMidPoint(myMidPoint);
eyesDistance = face.eyesDistance();
canvas.drawRect((int) (myMidPoint.x - eyesDistance),
(int) (myMidPoint.y - eyesDistance),
(int) (myMidPoint.x + eyesDistance),
(int) (myMidPoint.y + eyesDistance), myPaint);
}
}
}
}

Register Android Activity in Android Manifest File

<activity
            android:name="com.androidsurya.facemodule.FaceDetectorActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

Output ScreenShot
















Saturday, 22 October 2011

Android Alarm Service Example

Here below code is start alarm on particular time and stop alarm .

Here i create 2 buttons one is for start alarm after clicking on button 30 sec's and other stop alarm
button for stop.

Android UI Layout(main.xml)

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

    <Button
        android:id="@+id/startalarm"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Start Alarm" />

    <Button
        android:id="@+id/stopalarm"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Stop Alarm" />

</LinearLayout>

Android Alarm Service (AlarmService.java)

package com.androidsurya.androidalarm;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class AlarmService extends Service {
@Override
public void onCreate() {
// TODO Auto-generated method stub
Toast.makeText(this, "AlaramService onCreate() called.",
Toast.LENGTH_SHORT).show();
}

@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "AlaramService onBind() called.",
Toast.LENGTH_SHORT).show();
return null;

}

@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "AlaramService onDestroy() called.",
Toast.LENGTH_SHORT).show();

}

@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
// Here you can add your own code to play any sound using media player
Toast.makeText(this, "AlaramService onStart() called.",
Toast.LENGTH_SHORT).show();
}

@Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
// Here you can add your own code to media player which is all ready
// started early in onStart() method
Toast.makeText(this, "AlaramService onUnbind() called.",
Toast.LENGTH_SHORT).show();
return super.onUnbind(intent);

}
}

Android Activity(MainActivity.java)

package com.androidsurya.androidalarm;

import java.util.Calendar;

import com.androidsurya.androidalarm.R;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
PendingIntent pendingIntent;
Button startAlarm, stopAlarm;
AlarmManager alarmManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startAlarm = (Button) findViewById(R.id.startalarm);
stopAlarm = (Button) findViewById(R.id.stopalarm);
startAlarm.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(getApplicationContext(),
AlarmService.class);
pendingIntent = PendingIntent.getService(
getApplicationContext(), 0, myIntent, 0);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 30);
alarmManager.set(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(getApplicationContext(), "Start Alarm",
Toast.LENGTH_LONG).show();

}
});

stopAlarm.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
// Tell the user about what we did.
Toast.makeText(getApplicationContext(), "Stop Alarm!",
Toast.LENGTH_LONG).show();
}
});

}

}

Register Activity and Service in Android Manifest file

        <activity
            android:name="com.androidsurya.androidalarm.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>

        <service android:name=".AlarmService" />

Output Screenshot:



























































Thursday, 20 October 2011

Simple Android Service Example

What  is Service ?

A service is a component that runs in the background to perform long-running operations without needing to interact with the user. For example, a service might play music in the background while the user is in a different application, or it might fetch data over the network without blocking user interaction with an activity.

In Activity Simply calling this methods we can Start ,Stop the Service.
we can start Service using StartService() method and stop Service using StopService() method.

In Android To do background services Android Provide one Class i.e Service Class using this class we can perform background operations. 
In Service Class we are override these below methods  Start() and Destory() methods for starting an Service and Stop an Service.



First Create Your ownService Class which Extends Service (MyOwnService .java)

package com.androidsurya.serviceexample;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyOwnService extends Service {

@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}

@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "My Own Service Started....",
Toast.LENGTH_SHORT).show();
super.onStart(intent, startId);
}

@Override
public void onDestroy() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "My Own Service Stop....",
Toast.LENGTH_SHORT).show();
super.onDestroy();
}

}

Register the Service in Android Manifest File using Service Tag

<service android:name=".MyOwnService" />

UI Layout(activity_layout.xml)

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".ServiceUsingActivity" >

    <Button
        android:id="@+id/serviceOn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Service ON" />

    <Button
        android:id="@+id/serviceOFF"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Service OFF" />

</LinearLayout>


Android Activity Class(ServiceUsingActivity .java)

package com.androidsurya.serviceexample;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ServiceUsingActivity extends Activity {

Button serviceStart, serviceStop;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
serviceStart = (Button) findViewById(R.id.serviceOn);
serviceStart.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startService(new Intent(ServiceUsingActivity.this,
MyOwnService.class));
}
});
serviceStop = (Button) findViewById(R.id.serviceOFF);
serviceStop.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopService(new Intent(ServiceUsingActivity.this,
MyOwnService.class));

}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.service_using, menu);
return true;
}

}

Register Activity in Android Manifest File

    <activity
            android:name="com.androidsurya.serviceexample.ServiceUsingActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

Output ScreenShot:

















Tuesday, 11 October 2011

Android Copyright symbol in string (xml layout) Example

 So many people are think how to display the copyright symbol in your app.
 we can display copyright symbol in app using Unicode definition in a string.

Just see this below example:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    tools:ignore="HardcodedText" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="\u00A9 2011 androidsurya.blogspot.in"
        android:textSize="25dp" />
</RelativeLayout>

Output Screenshot:


Friday, 7 October 2011

Android Custom Toast in Service Example



Here the below code is use full for show Custom Toast message in Service

Toast UI Layout(custom_toast.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toast_layout_root"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:orientation="horizontal"
    android:paddingLeft="5dp"
    android:paddingRight="5dp" >
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/header"
        android:orientation="horizontal"
        android:paddingBottom="5dp"
        android:paddingTop="5dp" >
        <ImageView
            android:id="@+id/toastImg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:padding="3dp"/>
        <TextView
            android:id="@+id/toastMes"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:gravity="center_vertical"
            android:textColor="@android:color/white"
            android:textSize="7pt"
            android:padding="3dp"
            android:layout_marginRight="2dp"/>
    </LinearLayout>
</LinearLayout>

Call this Toast layout in Service using Below code

 LayoutInflater layoutInflater = (LayoutInflater)
 getSystemService(LAYOUT_INFLATER_SERVICE);
 View layout = inflater.inflate(R.layout.custom_toast, null);
 ImageView toastimg= (ImageView)
 layout.findViewById(R.id.toastImg);
 toastimg.setImageResource(R.drawable.anyimage);
TextView toastmes= (TextView)
 layout.findViewById(R.id.toastMes);
 toastmes.setText("Here your ur toast message");
 toast = new Toast(getApplicationContext());
 toast.setGravity(Gravity.BOTTOM, 0, 0);
 toast.setDuration(Toast.LENGTH_SHORT);
 toast.setView(layout);
 toast.show();

Tuesday, 4 October 2011

Android Multiple lines Edittext Example

In android we can create Edittext with multiple lines using below code in Layout

<LinearLayout 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"
    android:background="@android:color/black"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Multiline EditText"
        android:textColor="@android:color/white" />

    <EditText
        android:id="@+id/editext"
        android:layout_width="fill_parent"
        android:layout_height="150dip"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip"
        android:layout_marginTop="10dip"
        android:ems="150"
        android:gravity="left|top"
        android:hint="Please provide your comments here."
        android:inputType="textMultiLine|textCapSentences"
        android:padding="5dip"
        android:scrollbarAlwaysDrawVerticalTrack="true"
        android:textSize="20sp" >
    </EditText>

</LinearLayout>


Output Screen :











How to set space between Edittext lines android

In android we can set space between lines in Edittext using below attribute in Edittext.

Here XXX is a any value like... 1.3

    android:lineSpacingMultiplier="XXXdp"


Monday, 3 October 2011

How to take a screen shot programmatically

Here you can See take screen shot programmatically and display screen shot in Image View and and check weather SD card is in your device or not , To save screen shot in to the SD Card.

Xml(main.xml)

In main.xml Declare all view objects.


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/relativelayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<Button
android:id="@+id/btn_screenshoot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Click Here to Create ScreenShot" />

<ImageView
android:id="@+id/imgv_showscreenshot"
android:layout_width="216dp"
android:layout_height="360dp"
android:layout_below="@+id/btn_screenshoot"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp" />

</RelativeLayout>

Android Activity(ScreenshotActivity .java)

In this Activity we can see take a screenshot programatically when user click on Button.

package com.androidsurya.screenshot;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class ScreenshotActivity extends Activity {

Button btn_screenshoot;
int i = 0;
ImageView imgv_showscreenshot;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

btn_screenshoot = (Button) findViewById(R.id.btn_screenshoot);
btn_screenshoot.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

View view = findViewById(R.id.relativelayout);
view.setDrawingCacheEnabled(true);
Bitmap bitmap = view.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);
imgv_showscreenshot = (ImageView) findViewById(R.id.imgv_showscreenshot);
// set screenshot bitmapdrawable to imageview
imgv_showscreenshot.setBackgroundDrawable(bitmapDrawable);
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
// we check if external storage is available, otherwise
// display an error message to the user using Toast Message
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath()
+ "/ScreenShots");
directory.mkdirs();

String filename = "screenshot" + i + ".jpg";
File yourFile = new File(directory, filename);

while (yourFile.exists()) {
i++;
filename = "screenshot" + i + ".jpg";
yourFile = new File(directory, filename);
}

if (!yourFile.exists()) {
if (directory.canWrite()) {
try {
FileOutputStream out = new FileOutputStream(
yourFile, true);
bitmap.compress(Bitmap.CompressFormat.PNG, 90,
out);
out.flush();
out.close();
Toast.makeText(
ScreenshotActivity.this,
"File exported to /sdcard/ScreenShots/screenshot"
+ i + ".jpg",
Toast.LENGTH_SHORT).show();
i++;
} catch (IOException e) {
e.printStackTrace();
}

}
}
} else {
Toast.makeText(ScreenshotActivity.this,
"Sorry SD Card not available in your Device!",
Toast.LENGTH_SHORT).show();
}

}
});

}

}

 AndroidManifest.xml:

 In manifest file to store screenshot in sdcard
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
is mandatory. 

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidsurya.screenshot"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.androidsurya.screenshot.ScreenshotActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

Output Screenshot:






















Android SQLite Database Viewer or Debuging with Stetho

Every Android Developer uses SQLite Database to store data into the Android Application data. But to view the data in SQLite have a lot of...