Thursday 23 July 2015

progress-bar and downloading image with percentage




                          progress-bar and downloading image with percentage 



 Step1 .==> View => CircularProgressBar.java


package com.example.progressbarwithimagedwonload;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

public class CircularProgressBar extends View {

private int mDuration = 100;
private int mProgress = 30;
private Paint mPaint = new Paint();
private RectF mRectF = new RectF();
private int mBackgroundColor = Color.LTGRAY;
private int mPrimaryColor = Color.parseColor("#6DCAEC");
private float mStrokeWidth = 10F;

public interface OnProgressChangeListener {
public void onChange(int duration, int progress, float rate);

}

private OnProgressChangeListener mOnChangeListener;

public void setOnProgressChangeListener(OnProgressChangeListener l) {
mOnChangeListener = l;
}

public CircularProgressBar(Context context) {
super(context);
}

public CircularProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
}

public void setMax(int max) {
if (max < 0) {
max = 0;
}
mDuration = max;
}

public int getMax() {
return mDuration;
}

public void setProgress(int progress) {
if (progress > mDuration) {
progress = mDuration;
}
mProgress = progress;
if (mOnChangeListener != null) {
mOnChangeListener
.onChange(mDuration, progress, getRateOfProgress());
}
invalidate();
}

public int getProgress() {
return mProgress;
}

public void setBackgroundColor(int color) {
mBackgroundColor = color;
}

public void setPrimaryColor(int color) {
mPrimaryColor = color;
}

public void setCircleWidth(float width) {
mStrokeWidth = width;
}

@Override
protected synchronized void onDraw(Canvas canvas) {
super.onDraw(canvas);
int halfWidth = getWidth() / 2;
int halfHeight = getHeight() / 2;
int radius = halfWidth < halfHeight ? halfWidth : halfHeight;
float halfStrokeWidth = mStrokeWidth / 2;

mPaint.setColor(mBackgroundColor);
mPaint.setDither(true);
mPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(mStrokeWidth);
mPaint.setStyle(Paint.Style.STROKE);

canvas.drawCircle(halfWidth, halfHeight, radius - halfStrokeWidth,
mPaint);

mPaint.setColor(mPrimaryColor);
mRectF.top = halfHeight - radius + halfStrokeWidth;
mRectF.bottom = halfHeight + radius - halfStrokeWidth;
mRectF.left = halfWidth - radius + halfStrokeWidth;
mRectF.right = halfWidth + radius - halfStrokeWidth;
canvas.drawArc(mRectF, -90, getRateOfProgress() * 360, false, mPaint);
canvas.save();
}

private float getRateOfProgress() {
return (float) mProgress / mDuration;
}
}

Step 2 ==> Activity ====>MainActivity.java

package com.example.progressbarwithimagedwonload;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends ActionBarActivity {

private int progress = 0;

ImageView image_dwonloadimage;
Button btn_download;

private static String file_url = "http://chandandroid.uphero.com/tema_upload/uploads/chandru.jpg";

private RateTextCircularProgressBar mRateTextCircularProgressBar;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

image_dwonloadimage = (ImageView) findViewById(R.id.image_donwload);

mRateTextCircularProgressBar = (RateTextCircularProgressBar) findViewById(R.id.rate_progress_bar);
mRateTextCircularProgressBar.setMax(100);
mRateTextCircularProgressBar.clearAnimation();
mRateTextCircularProgressBar.getCircularProgressBar()
.setCircleWidth(20);

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

@Override
public void onClick(View v) {

new DownloadFileFromURL().execute(file_url);

}
});

}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
mRateTextCircularProgressBar.setProgress(msg.what);

if (progress >= 100) {
image_dwonloadimage.setVisibility(View.VISIBLE);
}
mHandler.sendEmptyMessageDelayed(progress++, 100);
super.handleMessage(msg);
}

};

class DownloadFileFromURL extends AsyncTask<String, String, String> {

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

@Override
protected String doInBackground(String... f_url) {

int count;
try {
URL url = new URL(f_url[0]);
URLConnection connection = url.openConnection();
connection.connect();

// /here getting file length;
int lengthoffile = connection.getContentLength();

// input stream to read file with 8k buffer

InputStream input = new BufferedInputStream(url.openStream(),
8192);

// write stream to write file.

String file_path = "/sdcard/CHANDRU";

File file = new File(file_path);

if (!file.exists()) {
file.mkdirs();
}

OutputStream output = new FileOutputStream(file_path
+ "/downloadedfile.jpg");
byte data[] = new byte[1024];

long total = 0;

while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lengthoffile));

// writing data to file
output.write(data, 0, count);
}

// flushing output
output.flush();

// closing streams
output.close();
input.close();

} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}

return null;

}

@Override
protected void onPostExecute(String result) {

// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory()
.toString() + "/CHANDRU/downloadedfile.jpg";
// setting downloaded into image view

image_dwonloadimage.setImageDrawable(Drawable
.createFromPath(imagePath));
}

protected void onProgressUpdate(String... progress) {
// / setting progress percentage
// pDialog.setProgress(Integer.parseInt(progress[0]));
mHandler.sendEmptyMessageDelayed(Integer.parseInt(progress[0]), 100);
mRateTextCircularProgressBar.setVisibility(View.VISIBLE);
}

}

}

Step 3 ==> FrameLayout ===> RateTextCircularProgressBar.java


package com.example.progressbarwithimagedwonload;


import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.example.progressbarwithimagedwonload.CircularProgressBar.OnProgressChangeListener;

/**
*
* @author kalidoss rajendran
*/

public class RateTextCircularProgressBar extends FrameLayout implements OnProgressChangeListener {

private CircularProgressBar mCircularProgressBar;
private TextView mRateText;
public RateTextCircularProgressBar(Context context) {
super(context);
init();
}
public RateTextCircularProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}

private void init() {
mCircularProgressBar = new CircularProgressBar(getContext());
this.addView(mCircularProgressBar);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
lp.gravity = Gravity.CENTER;
mCircularProgressBar.setLayoutParams(lp);
mRateText = new TextView(getContext());
this.addView(mRateText);
mRateText.setLayoutParams(lp);
mRateText.setGravity(Gravity.CENTER);
mRateText.setTextColor(Color.BLACK);
mRateText.setTextSize(20);
mCircularProgressBar.setOnProgressChangeListener(this);
}

public void setMax( int max ) {
mCircularProgressBar.setMax(max);
}

public void setProgress(int progress) {
mCircularProgressBar.setProgress(progress);
}

public CircularProgressBar getCircularProgressBar() {
return mCircularProgressBar;
}

public void setTextSize(float size) {
mRateText.setTextSize(size);
}

public void setTextColor( int color) {
mRateText.setTextColor(color);
}

@Override
public void onChange(int duration, int progress, float rate) {
mRateText.setText(String.valueOf( (int)(rate * 100 ) + "%"));
}
}

Step 4 ==> layout===> activity_main.xml



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg_image2"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Downloading Image With help of progressBar"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
    </LinearLayout>

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:padding="50dp" >

                <Button
                    android:id="@+id/btn_download"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Download..." />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" >

                <com.example.progressbarwithimagedwonload.RateTextCircularProgressBar
                    android:id="@+id/rate_progress_bar"
                    android:layout_width="75dp"
                    android:layout_height="75dp"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginBottom="30dp"
                    android:layout_marginTop="20dp"
                    android:visibility="invisible" >
                </com.example.progressbarwithimagedwonload.RateTextCircularProgressBar>

                <ImageView
                    android:id="@+id/image_donwload"
                    android:layout_width="250dp"
                    android:layout_height="250dp"
                    android:layout_gravity="center_horizontal"
                    android:src="@drawable/ic_launcher"
                    android:visibility="invisible" />
            </LinearLayout>
        </LinearLayout>
    </ScrollView>

</LinearLayout>


Step 5 : AndroidManifest.xml ===>

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.progressbarwithimagedwonload"
    android:versionCode="1"
    android:versionName="1.0" >

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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>

Example Screen :-


IMG-1



                                                                              IMG-2



IMG-3



 
Download  Source Code :-

                                 Download Source Code Progressbar and Download percentage Calculation.









Tuesday 7 July 2015

Repeating Alarm in Android Using Broad Cast Receiver



                                                        Repeating Alarm


Step 1:-


  MainActivity.java

package com.example.example_repeatingalarm;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity implements OnClickListener {

AlarmManager am;

Button btn_alearm;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

btn_alearm = (Button) findViewById(R.id.btn_alearm);
btn_alearm.setOnClickListener(this);

// Repeating Alarm using Timealarm Broadcastreceiver
setRepeatingAlarm();

}

@Override
public void onClick(View v) {

switch (v.getId()) {
case R.id.btn_alearm:

Toast.makeText(getApplicationContext(), "working",
Toast.LENGTH_SHORT).show();

Intent intent = new Intent(this, TimeAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (5 * 1000), pendingIntent);

default:
break;
}

}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

public void setRepeatingAlarm() {

Intent intent = new Intent(this, TimeAlarm.class);

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);

am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
(2 * 1000), pendingIntent);

System.out.println("Calling Alaram...");

}


}

Step 2:-

BroadcastReceiver class (TimeAlarm.java)


package com.example.example_repeatingalarm;

import java.io.File;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class TimeAlarm extends BroadcastReceiver {

NotificationManager nm;

int i = 0;

File myDir;

@Override
public void onReceive(Context context, Intent intent) {

nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);

CharSequence from = "Chandru";
CharSequence message = "Notification Test...";

PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(), 0);

Notification notif = new Notification(R.drawable.ic_launcher,
"simple testing...", System.currentTimeMillis());

notif.setLatestEventInfo(context, from, message, contentIntent);

nm.notify(i, notif);

i++;

}
}

Step 3 :-

            activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Repeating Aleram Example"
            android:textSize="40px" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingTop="125dp" >

        <Button
            android:id="@+id/btn_alearm"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Click Alearm" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingTop="140dp"
            android:text="Repeating Aleram using Broadcastreceiver."
            android:textSize="40dp" />
    </LinearLayout>

</LinearLayout>

Step 4:-

     AndroidManifest


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.example_repeatingalarm"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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>
        
        <receiver android:name=".TimeAlarm" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
        
        
    </application>

</manifest>


Step 5:- 

            Example Screen
 






Step 6:- 

         Download Full Source Code





Monday 6 July 2015

Image Canvas Using Android Application with source code




                                                           Image Canvas



Step 1:-

ChooseActivity.java

package com.example.paintapp;

import java.io.ByteArrayOutputStream;
import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class ChooseActivity extends Activity {

private final String TAG = getClass().getSimpleName();

public static final String BITMAP = "bitmap";
public static final String IMAGE_PATH = "imagePath";
private Button fromGallery, captureFromCamera;
private ImageView capturedImage;
public static final int SUCCESS = 1;
public static final int FAILURE = 2;

private static final int TAKE_PICTURE = 0;
private static final int EDIT_PICTURE = 1;
private static final int SELECT_PICTURE = 2;
private Uri mUri;
private File photoFile;
public static Bitmap mPhoto;
String JPEG_FILE_PREFIX = "IMG";

String JPEG_FILE_SUFFIX = ".jpg";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose);

// fromGallery = (Button) findViewById(R.id.chooseGallery);
captureFromCamera = (Button) findViewById(R.id.chooseCaptureFromCamera);

capturedImage = (ImageView) findViewById(R.id.capturedImage);

/*
* fromGallery.setOnClickListener(new OnClickListener() {
*
* @Override public void onClick(View v) { // TODO Auto-generated method
* stub Intent intent = new Intent(); intent.setType("image/*");
* intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(
* Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE); }
* });
*/
captureFromCamera.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
photoFile = new File(Environment.getExternalStorageDirectory(),
"photo.jpg");
mUri = Uri.fromFile(photoFile);
Intent intent = new Intent(ChooseActivity.this,
CameraActivity.class);
intent.putExtra(IMAGE_PATH, photoFile.getAbsolutePath());
startActivityForResult(intent, TAKE_PICTURE);
}
});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PICTURE && resultCode == SUCCESS) {
getContentResolver().notifyChange(mUri, null);
// ContentResolver cr = getContentResolver();
try {
// Log.v(TAG,"Orientation is : "+data.getIntExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,-1000));
new LoadCapturedImageTask().execute();
} catch (Exception e) {
}
} else if (requestCode == SELECT_PICTURE && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
photoFile = new File(getPath(selectedImageUri));
mUri = Uri.fromFile(photoFile);
getContentResolver().notifyChange(mUri, null);
new LoadCapturedImageTask().execute();
} else if (requestCode == EDIT_PICTURE
&& resultCode == FingerPaint.SUCCESS) {
Log.v(TAG, "Here too");

mPhoto = (Bitmap) data.getParcelableExtra(BITMAP);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
mPhoto.compress(Bitmap.CompressFormat.PNG, 100, bos);
Drawable drawable = new BitmapDrawable(getResources(), mPhoto);
capturedImage.setBackgroundDrawable(drawable);
}
}

public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

public static void displayAlert(Context context, String msg) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setMessage(context.getString(R.string.app_name));
alert.setMessage(msg);
alert.setPositiveButton(context.getString(R.string.btn_ok),
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub

}
});
alert.show();
}

private Bitmap rotateImage(Bitmap bitmap, int angle, int width, int height) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);

return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
}

class LoadCapturedImageTask extends AsyncTask<Void, Void, Void> {

ProgressDialog progress;

@Override
protected void onPreExecute() {
progress = ProgressDialog.show(ChooseActivity.this, "",
getString(R.string.msg_please_wait));
}

@Override
protected Void doInBackground(Void... params) {
/*
* mPhoto = android.provider.MediaStore.Images.Media.getBitmap(cr,
* mUri);
*/
BitmapFactory.Options o = new BitmapFactory.Options();
o.inSampleSize = 2;
Log.v(TAG, "Path : " + photoFile.getAbsolutePath());
mPhoto = BitmapFactory.decodeFile(photoFile.getAbsolutePath(), o)
.copy(Bitmap.Config.ARGB_8888, true);
int height = mPhoto.getHeight();
int width = mPhoto.getWidth();
/*
* Matrix matrix = new Matrix(); matrix.postRotate(90);
*
* mPhoto = Bitmap.createBitmap(mPhoto, 0, 0, width, height, matrix,
* true);
*/
mPhoto = rotateImage(mPhoto, 90, width, height);

getContentResolver().notifyChange(mUri, null);
Log.v(TAG,
"getOrientation : "
+ getOrientation(ChooseActivity.this,
photoFile.getAbsolutePath()));
return null;
}

@Override
protected void onPostExecute(Void result) {
progress.dismiss();
Intent intent = new Intent(ChooseActivity.this, FingerPaint.class);
intent.putExtra(BITMAP, mPhoto);
startActivityForResult(intent, EDIT_PICTURE);
}
}

public static int getOrientation(Context context, String imagePath) {
int rotate = 0;
try {
File imageFile = new File(imagePath);
ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);

switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}

Log.v("", "Exif orientation: " + orientation);
} catch (Exception e) {
e.printStackTrace();
}
return rotate;
}
}




Step 2:-

Activity_choose.xml

<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"
    android:gravity="center|top"
    tools:context=".ChooseActivity" >

    <ImageView
        android:id="@+id/capturedImage"
        android:layout_width="150dip"
        android:layout_height="200dip"
        android:layout_centerHorizontal="true" />
    <!--
         <Button
        android:id="@+id/chooseGallery"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/choose_gallery"
        android:layout_below="@id/capturedImage" />
    -->

    <Button
        android:id="@+id/chooseCaptureFromCamera"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/capturedImage"
        android:text="@string/capture_camera" />

</RelativeLayout>



Step 3:-

CameraActivity.java



package com.example.paintapp;

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

import android.app.Activity;
import android.content.Intent;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class CameraActivity extends Activity {
private SurfaceView preview = null;
private SurfaceHolder previewHolder = null;
private Camera camera = null;
private boolean inPreview = false;
private boolean cameraConfigured = false;
private Button btnCancel, btnCapture;

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

preview = (SurfaceView) findViewById(R.id.preview);
previewHolder = preview.getHolder();
previewHolder.addCallback(surfaceCallback);
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

btnCancel = (Button) findViewById(R.id.btnCancel);
btnCapture = (Button) findViewById(R.id.btnCapture);

btnCapture.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (inPreview) {
camera.takePicture(null, null, photoCallback);
inPreview = false;
}
}
});

btnCancel.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
// AddReportItemActivity.mPhoto =
// drawView.getDrawingCache();
setResult(ChooseActivity.FAILURE, intent);
finish();
}
});
}

@Override
public void onResume() {
super.onResume();

/*
* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
* Camera.CameraInfo info = new Camera.CameraInfo();
* for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
* Camera.getCameraInfo(i, info);
* if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { camera =
* Camera.open(i); } } }
*/

// if (camera == null) {
camera = Camera.open();
// }

startPreview();
}

@Override
public void onPause() {
if (inPreview) {
camera.stopPreview();
}

if (camera != null) {
camera.release();
camera = null;
}

inPreview = false;

super.onPause();
}

/*
* @Override public boolean onCreateOptionsMenu(Menu menu) { new
* MenuInflater(this).inflate(R.menu.activity_camera, menu);
* return (super.onCreateOptionsMenu(menu)); }
*/

private Camera.Size getBestPreviewSize(int width, int height,
Camera.Parameters parameters) {
Camera.Size result = null;

for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
if (size.width <= width && size.height <= height) {
if (result == null) {
result = size;
} else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;

if (newArea > resultArea) {
result = size;
}
}
}
}

return (result);
}

private Camera.Size getSmallestPictureSize(Camera.Parameters parameters) {
Camera.Size result = null;

for (Camera.Size size : parameters.getSupportedPictureSizes()) {
if (result == null) {
result = size;
} else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;

if (newArea < resultArea) {
result = size;
}
}
}

return (result);
}

private void initPreview(int width, int height) {
if (camera != null && previewHolder.getSurface() != null) {
try {
camera.setPreviewDisplay(previewHolder);
} catch (Throwable t) {
Log.e("PreviewDemo-surfaceCallback",
"Exception in setPreviewDisplay()", t);
Toast.makeText(CameraActivity.this, t.getMessage(),
Toast.LENGTH_LONG).show();
}

if (!cameraConfigured) {
Camera.Parameters parameters = camera.getParameters();
Camera.Size size = getBestPreviewSize(width, height, parameters);
Camera.Size pictureSize = getSmallestPictureSize(parameters);

if (size != null && pictureSize != null) {
parameters.setPreviewSize(size.width, size.height);
parameters.setPictureSize(pictureSize.width,
pictureSize.height);
parameters.setPictureFormat(ImageFormat.JPEG);
camera.setParameters(parameters);
cameraConfigured = true;
}
}
}
}

private void startPreview() {
if (cameraConfigured && camera != null) {
camera.setDisplayOrientation(90);
camera.startPreview();
inPreview = true;
}
}

SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
public void surfaceCreated(SurfaceHolder holder) {
// no-op -- wait until surfaceChanged()
}

public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
initPreview(width, height);
startPreview();
}

public void surfaceDestroyed(SurfaceHolder holder) {
// no-op
}
};

Camera.PictureCallback photoCallback = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
new SavePhotoTask().execute(data);
// camera.startPreview();
// inPreview=true;
}
};

class SavePhotoTask extends AsyncTask<byte[], String, Integer> {
@Override
protected Integer doInBackground(byte[]... jpeg) {
File photo = new File(getIntent().getStringExtra(
ChooseActivity.IMAGE_PATH));

if (photo.exists()) {
photo.delete();
}

try {
FileOutputStream fos = new FileOutputStream(photo.getPath());

fos.write(jpeg[0]);
fos.close();
} catch (java.io.IOException e) {
return ChooseActivity.FAILURE;
}
return ChooseActivity.SUCCESS;
}

@Override
protected void onPostExecute(Integer result) {
if (result == ChooseActivity.SUCCESS) {
Intent intent = new Intent();
// AddReportItemActivity.mPhoto =
// drawView.getDrawingCache();
setResult(ChooseActivity.SUCCESS, intent);
finish();
} else {
Intent intent = new Intent();
// AddReportItemActivity.mPhoto =
// drawView.getDrawingCache();
setResult(ChooseActivity.FAILURE, intent);
finish();
}
}
}
}


Step 4:- 


Activity_camera.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" >

    <android.view.SurfaceView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/preview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" >
    </android.view.SurfaceView>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/title_bar" >

        <Button android:id="@+id/btnCapture"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/text_selector"
            android:layout_centerInParent="true" />
        <Button android:id="@+id/btnCancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/cancel"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dip" />
    </RelativeLayout>

</LinearLayout>



Step 5:-

Screenshot



Capture Image


two : name 







Tap setting.



final image.




Source Code :


                                                   Download Full Source Code Here...


*************************************************************************Thank You Viewers************************************